示例#1
0
        public void AlignCameraRotationWithTrack()
        {
            UnityEditor.Undo.RecordObject(transform, ALIGN_ROTATION_FUNCTION_NAME);

            TrackPath track = FindObjectOfType <TrackPath>();

            if (track == null)
            {
                Debug.LogError("No track path found in scene; cannot align camera with track.", this);
                return;
            }

            if (track.LinearPath == null)
            {
                track.GenLinearPath();
            }

            Vector3 pointOnPath;
            Vector3 trackDirection;
            Vector3 trackRight;

            track.LinearPath.GetClosestPointOnPath(transform.position, out pointOnPath, out trackDirection, out trackRight, true);
            Vector3 trackUp = Vector3.Cross(trackDirection, trackRight);

            Debug.DrawLine(transform.position, pointOnPath, Color.green, 5f);
            Debug.DrawLine(pointOnPath, pointOnPath + trackUp * 2.5f, Color.green, 5f);

            transform.SetLookRotation(trackDirection, trackUp);
        }
示例#2
0
    protected virtual void OnDrawGizmosSelected()
    {
        if (!Application.isPlaying)
        {
            FixedUpdate();
        }

        if (waypoints == null)
        {
            waypoints = GetComponentInParent <TrackGeometry>();
        }

        if (waypoints == null)
        {
            return;
        }

        var query = waypoints.Query(Distance);

        var midline = query.Midpoint;
        var forward = query.Forward;

        Gizmos.color = Color.green;
        Gizmos.DrawLine(midline, position);
        Gizmos.color = Color.red;
        Gizmos.DrawRay(midline, forward);
    }
示例#3
0
    public static void PlacePrefab(Transform car, TrackPath geometry, float distance, float offset)
    {
        var q = geometry.Query(distance);

        car.position = q.Midpoint + (q.Tangent * offset) + car.localPosition;
        car.forward  = q.Forward;
        car.up       = q.Up;
    }
示例#4
0
    public bool CheckPosition(TrackPath path, float position)
    {
        if (path.Flags(position).nospawn)
        {
            return(false);
        }

        return(true);
    }
示例#5
0
    public static TrackPath CreateBigTrackPath(string resourceString, int lapsCount)
    {
        GameObject testTrackPathPrefab = Resources.Load <GameObject>(resourceString);

        testTrackPathPrefab.GetComponent <TrackPath>().countOfLaps = lapsCount;
        TrackPath path = UnityEngine.Object.Instantiate(testTrackPathPrefab)
                         .GetComponent <TrackPath>();

        return(path);
    }
示例#6
0
    public PathCache(TrackPath path, float resolution)
    {
        this.path       = path;
        this.resolution = resolution;

        table = new PathQuery[Mathf.CeilToInt(path.totalLength / resolution)];
        for (float d = 0; d < path.totalLength; d += resolution)
        {
            table[Lower(d)] = path.Query(d);
        }
    }
示例#7
0
    public ProfileAgent CreateAgent(TrackPath path, float position)
    {
        var container = path.transform.Find("Agents");

        if (!container)
        {
            container = new GameObject("Agents").transform;
            container.SetParent(path.transform);
        }

        Util.SetLayer(AgentPrefab, TrainingProperties.AgentLayer); // for now car but we may add a training car layer in the future

        var agent = GameObject.Instantiate(AgentPrefab, container);

        agent.name = agent.name + " " + agents.Count;

        var driver = agent.GetComponent <ProfileController>();

        DestroyImmediate(driver);

        var navigator = agent.GetComponent <PathNavigator>(); // ensure navigator is initialised first as profile agent will reset it

        navigator.waypoints        = path;
        navigator.StartingPosition = position;

        var tracknavigator = agent.GetComponentInChildren <TrackNavigator>();

        if (tracknavigator != null)
        {
            DestroyImmediate(tracknavigator); // don't need this so dont waste cpu time
        }

        var profileAgent = agent.GetComponent <ProfileAgent>();

        if (!profileAgent)
        {
            profileAgent = agent.AddComponent <ProfileAgent>();
        }

        profileAgent.profileLength = profileLength;
        profileAgent.speedStepSize = profileSpeedStepSize;
        profileAgent.interval      = driver.observationsInterval;

        profileAgent.CreateProfile(); // re-create the profile with the updated parameters as CreateProfile will be called with the prefabs parameters by PathFinder.Awake() on AddComponent
        profileAgent.Reset();

        agent.SetActive(true); // prefab may be disabled depending on when it was last updated

        return(profileAgent);
    }
    private void OnSelectionChange()
    {
        if (!Selection.activeGameObject)
        {
            return;
        }
        TrackPath tPath = Selection.activeGameObject.GetComponent <TrackPath>();

        if (tPath)
        {
            selectedGameObject = Selection.activeGameObject;
            trackPath          = tPath;
            Repaint();
        }
    }
    public PlayerPilotController(PlayerPilotModelView player, ShipModelView ship, TrackPath checkpoints, DirectionArrowModelView dirHUDArrow)
    {
        playerModelView = player;
        shipModelView   = ship;
        checkpointsPath = checkpoints;
        directionArrow  = dirHUDArrow;

        checkpointsPath.SetObjPosition(shipModelView.transform, ship, true, true);
        directionArrow.CheckpointDirection = checkpointsPath.GetNextGatePoint(shipModelView.transform);
        directionArrow.ShipDirection       = shipModelView.transform;

        playerModelView.OnMovingInput       += HandleMovingInput;
        InputControl.Instance.OnActionInput += HandleActionInput;

        playerModelView.OnTriggerCollision += HandleTriggerCollision;
    }
 /// <summary>
 /// Add information about the closest vector section
 /// </summary>
 /// <param name="trackViewer"></param>
 private void AddVectorSectionStatus(TrackViewer trackViewer)
 {
     if (Properties.Settings.Default.statusShowVectorSections)
     {
         TrVectorSection tvs = trackViewer.DrawTrackDB.ClosestTrack.VectorSection;
         if (tvs == null)
         {
             return;
         }
         uint   shapeIndex = tvs.ShapeIndex;
         string shapeName  = "Unknown:" + shapeIndex.ToString(System.Globalization.CultureInfo.CurrentCulture);
         try
         {
             // Try to find a fixed track
             TrackShape shape = trackViewer.RouteData.TsectionDat.TrackShapes.Get(shapeIndex);
             shapeName = shape.FileName;
         }
         catch
         {
             // try to find a dynamic track
             try
             {
                 TrackPath trackPath = trackViewer.RouteData.TsectionDat.TSectionIdx.TrackPaths[tvs.ShapeIndex];
                 shapeName = "<dynamic ?>";
                 foreach (uint trackSection in trackPath.TrackSections)
                 {
                     if (trackSection == tvs.SectionIndex)
                     {
                         shapeName = "<dynamic>";
                     }
                     // For some reason I do not undestand the (route) section.tdb. trackpaths are not consistent tracksections
                     // so this foreach loop will not always find a combination
                 }
             }
             catch
             {
             }
         }
         statusAdditional.Text += string.Format(System.Globalization.CultureInfo.CurrentCulture,
                                                " VectorSection ({3}/{4}) filename={2} Index={0} shapeIndex={1}",
                                                tvs.SectionIndex, shapeIndex, shapeName,
                                                trackViewer.DrawTrackDB.ClosestTrack.TrackVectorSectionIndex + 1,
                                                trackViewer.DrawTrackDB.ClosestTrack.TrackNode.TrVectorNode.TrVectorSections.Count());
     }
 }
        public void RecalculateTrackPosition()
        {
            TrackPath track = CinematicCameraTriggerManager.Instance.TrackPath;

            if (track.LinearPath == null)
            {
                CinematicCameraTriggerManager.Instance.TrackPath.GenLinearPath();
            }

            float distanceToPoint; // unused

            track.LinearPath.GetClosestPointOnPath(transform.position, out closestPointOnTrack, out trackDirection, out trackPerpendicular, out distanceAlongTrack, out distanceToPoint, false);
            percentageAlongTrack = distanceAlongTrack / track.Distance * 100f;
            transform.position   = closestPointOnTrack;

            UpdateName();
            CinematicCameraTriggerManager.Instance.UpdateCameraTriggersIfNecessary(true);
        }
示例#12
0
    public void AttachTo( TrackPath otherPath )
    {
        Transform otherTransform = otherPath.FinishTransform();

        transform.rotation = otherTransform.rotation;

        if ( paths.Length > 0 )
        {
            TrackPath firstPath = GetFirstPath();

            Vector3 toOther = otherTransform.position - firstPath.StartTransform().position;
            transform.position += toOther;
        }
        else
        {
            transform.position = otherTransform.position;
        }
    }
    void CalcTiltValue( TrackPath path )
    {
        tiltValue = 0f;

        int numChoices = path.nextPath.Length;

        if ( numChoices < 2 )
            return;

        foreach ( TrackPath possiblePath in path.nextPath )
        {
            if ( possiblePath.nextPath.Length < 1 )
                continue;

            // TODO - add three-way split handling

            tiltValue = possiblePath.DirectionVector.normalized.x;
        }
    }
示例#14
0
    private int runOutDirection = 2;  // TODO переделать этот костыль

    public EnemyPilotController(EnemyPilotModelView enemyPilot, ShipModelView ship, TrackPath checkpoints)
    {
        pilotModelView  = enemyPilot;
        shipModelView   = ship;
        checkpointsPath = checkpoints;



        checkpointsPath.SetObjPosition(ship.transform, shipModelView, true);
        currentAim = checkpointsPath.GetStartPosition();

        pilotModelView.ChechpointTarget    = currentAim.position;
        pilotModelView.OnMovingInput      += HandleMovingInput;
        pilotModelView.OnActionInput      += HandleActionInput;
        pilotModelView.OnTriggerCollision += HandleTriggerCollision;

        shipModelView.OnSecondaryAbilityChanged += HandleShipSecondaryAbilityChanged;
        SetAimAndOffset();
    }
示例#15
0
    public Agent CreateAgent(TrackPath track, float coefficient)
    {
        var container = track.transform.Find("Agents");

        if (!container)
        {
            container = new GameObject("Agents").transform;
            container.SetParent(track.transform);
        }

        var agent = GameObject.Instantiate(AgentPrefab, container);

        agent.name = agent.name + " " + agents.Count;

        var path = agent.gameObject.AddComponent <InterpolatedPath>();

        path.coefficient = coefficient;
        path.Initialise();

        var navigator = agent.GetComponent <PathNavigator>();

        navigator.waypoints        = path;
        navigator.StartingPosition = 0;

        ResetController.ResetPosition(navigator);

        agent.SetActive(true);                          // prefab may be disabled depending on when it was last updated
        SetLayer(agent, TrainingProperties.AgentLayer); // for now car but we may add a training car layer in the future

        return(new Agent()
        {
            navigator = navigator,
            path = path,
            times = new float[path.waypoints.Count]
        });
    }
示例#16
0
        public async Task <int?> AddPath(string location)
        {
            int?id = default(int?);

            if (!string.IsNullOrWhiteSpace(location))
            {
                object    parameters = new { location };
                TrackPath path       = new TrackPath(location),
                          dbPath     = await dataService.Get <TrackPath>(item => item.Location.Trim() == location.Trim());

                if (dbPath != null)
                {
                    id = dbPath.Id;
                }
                else
                {
                    await dataService.Insert(path);

                    id = path.Id;
                }
            }

            return(id);
        }
示例#17
0
 public static PlayerPilotController CreatePlayerPilotController(PlayerPilotModelView playerMV, ShipModelView shipMV, TrackPath checkpoints, DirectionArrowModelView dirArrowHUD)
 {
     return(new PlayerPilotController(playerMV, shipMV, checkpoints, dirArrowHUD));
 }
 void OnReachedNewPath( TrackPath newPath )
 {
     CalcTiltValue( newPath );
 }
示例#19
0
 public Experience(TrackPath path)
 {
     this.path     = path;
     this.profiles = new List <List <ProfileAgent.Node> >();
 }
    public GameController(Canvas mainCanvas, Camera mainCam, GameStats gameStat, int lapsCount, int shipCount) // конструктор игры, можно сделать несколько конструкторов(например сколько противников, какая сложность, какая трасса)
    {
        mainCamera    = mainCam;
        objectsInGame = new List <GameObject>();
        canvas        = mainCanvas;
        gameStats     = gameStat;

        //создаем трассу
        trackMV          = TrackFactory.CreateBigTrackModelView(gameStats.testTrackPrefab); // создаем трассу и добавляем в лист объектов в игре
        trackMV.OnPause += HandleGamePause;                                                 // подписываем обработчик паузы на событие паузы
        objectsInGame.Add(trackMV.gameObject);

        //создаем сеть чекпоинтов
        checkpointsPath           = TrackFactory.CreateBigTrackPath(gameStats.testTrackPathPrefab, lapsCount);
        checkpointsPath.OnFinish += HandleTrackFinish;
        objectsInGame.Add(checkpointsPath.gameObject);

        // создаем объект размещения кораблей на трассе
        StartPlacerModelView placerMV = TrackFactory.CreateStartPlacer(checkpointsPath.GetStartPosition(), gameStats.placerPrefab);

        // создаем корабль игрока
        ShipModelView  playerShipMV   = ShipFactory.CreateShipModelView(placerMV.GetSpawnPoint(0));
        ShipController shipController = ShipFactory.CreateShipController(playerShipMV, null);

        playerShipMV.gameObject.AddComponent <AudioListener>();
        objectsInGame.Add(playerShipMV.gameObject);

        playerShipMV.name = "Player";

        ///Создаем эффект песчаной бури и привязываем к игроку
        EffectModelView effectModelView = EffectsFactory.CreateSandstormEffect(gameStats.sandStormPrefab);

        effectModelView.transform.parent   = playerShipMV.transform;
        effectModelView.transform.position = playerShipMV.transform.position;

        // создаем HUD стрелку направления
        DirectionArrowModelView HUDarrowMV = UIFactory.CreateDirectionArrow(canvas);

        // создаем пилота игрока
        PlayerPilotModelView  playerPilotMV    = PilotFactory.CreatePlayerPilotModelView(playerShipMV.transform);
        PlayerPilotController playerController = PilotFactory.CreatePlayerPilotController(playerPilotMV, playerShipMV, checkpointsPath, HUDarrowMV);

        objectsInGame.Add(playerPilotMV.gameObject);
        UIFactory.AddMinimapPointToPlayer(playerPilotMV.transform);


        for (int i = 1; i < shipCount; i++)
        {
            // создаем корабль противника
            ShipModelView enemyShipMV = ShipFactory.CreateShipModelView(placerMV.GetSpawnPoint(i));
            objectsInGame.Add(enemyShipMV.gameObject);

            enemyShipMV.name = $"Enemy {i}";

            // создаем показатель хитпоинтов корабля противника
            HitpointsCanvasModelView enemyHp = UIFactory.CreateShipHealthBar(enemyShipMV.transform);
            if (enemyHp == null)
            {
                Debug.Log("HP NOT CREATED!!");
            }
            objectsInGame.Add(enemyHp.gameObject);

            // создаем контроллер корабля противника
            ShipController enemyShipController = ShipFactory.CreateShipController(enemyShipMV, enemyHp);

            // создаем пилота противника
            EnemyPilotModelView  enemyPilotMV         = PilotFactory.CreateEnemyPilotModelView(enemyShipMV.transform);
            EnemyPilotController enemyPilotController =
                PilotFactory.CreateEnemyPilotController(enemyPilotMV, enemyShipMV, checkpointsPath);
            enemyShipMV.enemyPilotController = enemyPilotController;
            objectsInGame.Add(enemyPilotMV.gameObject);

            UIFactory.AddMinimapPointToEnemy(enemyPilotMV.transform);
        }

        // TODO создаем HUD отображение способностей (ТЕСТОВОЕ!!!)
        AbilityHUDModelView abilityHUDMV = UIFactory.CreatePlayerAbilityUI(canvas);

        objectsInGame.Add(abilityHUDMV.gameObject);
        AbilityHUDController abilityHUDController = new AbilityHUDController(abilityHUDMV, playerShipMV);

        // создаем риг камер
        CinemachineModelView cameraMV = CameraFactory.CreateCameraRig(playerShipMV.transform);

        mainCamera.gameObject.SetActive(false);  // отключаем основную камеру после появления рига
        objectsInGame.Add(cameraMV.gameObject);



        //Создание синглтона Ввода данных от пользователя
        GameObject inputController = new GameObject();

        inputController.AddComponent <InputControl>();
        objectsInGame.Add(inputController);

        //Создание синглтона контроля за TimeScale
        GameObject timeFollowController = new GameObject();

        timeFollowController.AddComponent <TimeFollowController>();
        objectsInGame.Add(timeFollowController);

        // создаем окно оповещений
        alertsModelView = UIFactory.CreateAlertsModelView(canvas);
        objectsInGame.Add(alertsModelView.gameObject);


        //Создаём окно позиции в гонке:
        TrackPositionModelView trackposMenuModel = UIFactory.CreateTrackPositionModelView(canvas);

        trackposMenuModel.trackPath = checkpointsPath;
        objectsInGame.Add(trackposMenuModel.gameObject);

        // создаем миникарту
        GameObject minimapCamera = UnityEngine.Object.Instantiate(Resources.Load <GameObject>("Prefabs/MinimapCamera"));

        objectsInGame.Add(minimapCamera);
        GameObject miniMap = UIFactory.CreateMinimapObj(canvas);

        objectsInGame.Add(miniMap);
    }
        private void CalculateAverageRankForPath(TrackPath path)
        {
            if (path.AverageRank == 0 || path.Tracks.Count < 3)
            {
                path.AverageRank = GetAverageTrackAndMixAndKeyRank(path.Tracks);
            }
            else
            {
                var track1 = path.Tracks[path.Tracks.Count - 2];
                var track2 = path.Tracks[path.Tracks.Count - 1];
                var trackRank = GetAverageTrackAndMixAndKeyRank(track1, track2);

                path.AverageRank = (((path.Tracks.Count - 1)*path.AverageRank) + trackRank)/path.Tracks.Count;
            }
        }
示例#22
0
 private void FindTrackPath()
 {
     trackPath = FindObjectOfType <TrackPath>();
 }
 public TrackPath(Track newTrack, TrackPath existingTracks)
     : this(newTrack, existingTracks.Tracks)
 {
     AverageRank = existingTracks.AverageRank;
 }
示例#24
0
    public void Traverse( float deltaTime )
    {
        if ( currentPath == null )
            return;

        float moveDelta = currentSpeed * deltaTime;

        float lengthRemaining = ( 1 - progress ) * currentPath.Length;

        // TODO cleanup, make while loop?
        if ( moveDelta > lengthRemaining )
        {
            moveDelta -= lengthRemaining;

            currentPath = currentPath.SelectNextPath( GetTiltValue() );

            if ( currentPath == null )
            {
                playerGameObject.FormOfDeath("deadend");
                playerGameObject.Kill();
                return;
            }
            else
            {
                ChangeTiltValueAtPathChange();
                SendMessage( "OnReachedNewPath", currentPath, SendMessageOptions.DontRequireReceiver );
            }

            progress = 0;
            lengthRemaining = ( 1 - progress ) * currentPath.Length;
        }

        float progressDelta = moveDelta / currentPath.Length;

        progress += progressDelta;

        transform.position = currentPath.PointAt( progress );

        LookAhead();
    }
示例#25
0
    // Use this for initialization
    void Start()
    {
        playerGameObject = GetComponent<Player>();

        currentPath = startPiece.GetFirstPath();

        currentSpeed = ConvertFromMPH(initialSpeedInMPH);
        deceleration = (ConvertFromMPH(20f) - currentSpeed) / 10f;
    }
        public List<Track> GeneratePlayList(List<Track> availableTracks,
            MixLibrary mixLibrary,
            List<Track> currentPlaylist,
            Direction direction,
            int approximateLength,
            AllowBearableMixStrategy allowBearable,
            MixStrategy strategy,
            UseExtendedMixes useExtendedMixes,
            Dictionary<string, Dictionary<string, Track>> excludedMixes,
            bool restrictArtistClumping,
            bool restrictGenreClumping,
            bool restrictTitleClumping,
            ContinueMix continueMix,
            KeyMixStrategy keyMixStrategy,
            int maxTracksToAdd)
        {
            if (strategy == MixStrategy.Working && currentPlaylist.Count == 0) return currentPlaylist;

            Track workingTrack = null;
            if (strategy == MixStrategy.Working)
            {
                direction = Direction.Any;
                workingTrack = currentPlaylist.Last();
            }

            GeneratePlayListStatus = "";
            MixLibrary = mixLibrary;

            AvailableTracks = availableTracks;

            if (strategy == MixStrategy.Working) AvailableTracks.RemoveAll(t => MixLibrary.GetMixOutCount(t) == 0);

            if (AvailableTracks.Count == 0) return currentPlaylist;

            var availableTrackDescriptions = GetDistinctTrackDescriptions(AvailableTracks);

            var trackCountLimit = int.MaxValue;
            if (approximateLength > 0 && approximateLength != int.MaxValue)
            {
                var currentLength = currentPlaylist.Sum(cp => cp.Length);
                var requiredLength = Convert.ToInt32((approximateLength*60) - currentLength);

                if (requiredLength <= 0) return new List<Track>();
                var averageLength = AvailableTracks.Average(t => t.Length);

                trackCountLimit = (requiredLength/Convert.ToInt32(averageLength)) + currentPlaylist.Count;

                if (trackCountLimit == currentPlaylist.Count) return new List<Track>();
            }

            if (maxTracksToAdd != int.MaxValue && trackCountLimit > currentPlaylist.Count + maxTracksToAdd)
            {
                trackCountLimit = currentPlaylist.Count + maxTracksToAdd;
            }

            if (strategy != MixStrategy.Unranked && strategy != MixStrategy.Working)
            {
                if (trackCountLimit > AvailableTracks.Count)
                {
                    trackCountLimit = AvailableTracks.Count;
                }
            }

            var initialPlaylistCount = currentPlaylist.Count;

            var currentPaths = new List<TrackPath>();
            if (currentPlaylist.Count == 0)
            {
                var trackPaths = AvailableTracks.Select(track => new TrackPath(track));
                foreach (var path in trackPaths)
                {
                    CalculateAverageRankForPath(path);
                    currentPaths.Add(path);
                }
            }
            else if (continueMix == ContinueMix.No)
            {
                var trackPaths = AvailableTracks
                    .Select(track => new List<Track>(currentPlaylist) {track})
                    .Select(playlist => new TrackPath(playlist));

                foreach (var path in trackPaths)
                {
                    CalculateAverageRankForPath(path);
                    currentPaths.Add(path);
                }
            }
            else
            {
                var path = new TrackPath(currentPlaylist);
                CalculateAverageRankForPath(path);
                currentPaths.Add(path);
            }

            _cancelGeneratePlayList = false;
            _stopGeneratePlayList = false;

            var nextPaths = new List<TrackPath>();
            while (!IsGenerationHalted())
            {
                ParallelHelper.ForEach(currentPaths, currentPath => GeneratePaths(direction,
                    allowBearable,
                    strategy,
                    useExtendedMixes,
                    excludedMixes,
                    restrictArtistClumping,
                    restrictGenreClumping,
                    restrictTitleClumping,
                    keyMixStrategy,
                    workingTrack,
                    availableTrackDescriptions,
                    nextPaths,
                    currentPath));

                if (IsGenerationHalted()) break;

                if (nextPaths.Count == 0) break;

                GeneratePlayListStatus =
                    $"Generated {nextPaths.Count} possible paths for {nextPaths[0].Tracks.Count} of {trackCountLimit} tracks.";

                var max = 50*Environment.ProcessorCount;

                if (nextPaths.Count > max)
                {
                    nextPaths = nextPaths
                        .OrderByDescending(t => t.AverageRank)
                        .Take(max)
                        .ToList();
                }

                currentPaths.Clear();
                currentPaths.AddRange(nextPaths);

                if (nextPaths[0].Tracks.Count >= trackCountLimit) break;
                nextPaths.Clear();
            }

            if (_cancelGeneratePlayList) return currentPlaylist;

            var resultPath = currentPaths
                .OrderByDescending(t => GetAverageTrackAndMixAndKeyRank(t.Tracks))
                .FirstOrDefault();

            if ((strategy == MixStrategy.BestMix || strategy == MixStrategy.Variety ||
                 strategy == MixStrategy.ExtraVariety)
                && resultPath != null
                && resultPath.Tracks.Count < trackCountLimit
                && resultPath.Tracks.Count > 0)
            {
                availableTrackDescriptions = GetDistinctTrackDescriptions(AvailableTracks);
                var excludeTrackDescriptions = GetDistinctTrackDescriptions(resultPath.Tracks);
                var currentTrack = resultPath.Tracks[resultPath.Tracks.Count - 1];
                var nextTrack =
                    GetBestMixTracks(currentTrack, resultPath.Tracks, allowBearable, availableTrackDescriptions,
                        excludeTrackDescriptions, restrictArtistClumping, restrictArtistClumping, restrictTitleClumping,
                        keyMixStrategy)
                        .OrderBy(t => GetAverageTrackAndMixAndKeyRank(currentTrack, t))
                        .FirstOrDefault();

                if (nextTrack != null) resultPath.Tracks.Add(nextTrack);
            }

            var resultTracks = (resultPath != null)
                ? resultPath.Tracks
                : new List<Track>();

            if (continueMix == ContinueMix.IfPossible && resultTracks.Count == initialPlaylistCount)
            {
                return GeneratePlayList(availableTracks,
                    mixLibrary,
                    currentPlaylist,
                    direction,
                    approximateLength,
                    allowBearable,
                    strategy,
                    useExtendedMixes,
                    excludedMixes,
                    restrictArtistClumping,
                    restrictGenreClumping,
                    restrictTitleClumping,
                    ContinueMix.No,
                    keyMixStrategy,
                    maxTracksToAdd);
            }

            return resultTracks;
        }
示例#27
0
 public static EnemyPilotController CreateEnemyPilotController(EnemyPilotModelView enemyMV, ShipModelView shipMV, TrackPath checkpoints)
 {
     return(new EnemyPilotController(enemyMV, shipMV, checkpoints));
 }
示例#28
0
    private void Start()
    {
        if (creation.Count == 0)
        {
            return;
        }

        trackPath          = GetComponent <TrackPath>();
        pointsAndPrefabs   = new Dictionary <GameObject, GameobjectsToCreate>();
        pointsAndCreations = new Dictionary <GameObject, GameObject>();
        listOfPoints       = new List <GameObject>();


        //определяем количество создаваемых объектов
        int sumPointToCreate = 0;

        foreach (GameobjectsToCreate gameobjectsToCreate in creation)
        {
            sumPointToCreate += gameobjectsToCreate.count;
        }

        //Длина интервала между точками спавна объектов
        float entitieDistance = trackPath.GetTrackDistance() / (sumPointToCreate + 1);
        float currentDistance = 0.5f;

        //создаём точки спавна объектов
        for (int i = 0; i < sumPointToCreate; i++)
        {
            currentDistance += entitieDistance;

            KeyValuePair <Transform, float> cKVP = trackPath.GetChekpointThrouDistance(currentDistance);


            Vector3 curPoint  = cKVP.Key.position;
            Vector3 nextPoint = trackPath.GetNextCheckPointPosition(cKVP.Key).position;
            float   m1        = currentDistance - cKVP.Value;
            float   m2        = Vector3.Distance(curPoint, nextPoint) - m1;

            float x = (m2 * curPoint.x + m1 * nextPoint.x) / (m1 + m2);
            float y = (m2 * curPoint.y + m1 * nextPoint.y) / (m1 + m2);
            float z = (m2 * curPoint.z + m1 * nextPoint.z) / (m1 + m2);



            Vector3 posToCreate = new Vector3(x, y + 100f, z);

            GameObject pointOfCreation = Instantiate(pointCreator, posToCreate, Quaternion.identity, gameObject.transform);

            Vector3 posToLookAt = nextPoint;
            posToLookAt.y = pointOfCreation.transform.position.y;

            pointOfCreation.transform.LookAt(posToLookAt);

            pointsAndCreations.Add(pointOfCreation, default);
            listOfPoints.Add(pointOfCreation);
        }

        ///создаём Список всех создаваемых префабов по их количеству
        List <GameobjectsToCreate> creaturesCountList = new List <GameobjectsToCreate>();

        foreach (var item in creation)
        {
            for (int i = 0; i < item.count; i++)
            {
                creaturesCountList.Add(item);
            }
        }

        //раздаём точкам тип префаба
        foreach (GameObject pointOfSpawn in listOfPoints)
        {
            int curRnd = UnityEngine.Random.Range(0, creaturesCountList.Count);

            pointsAndPrefabs.Add(pointOfSpawn, creaturesCountList[curRnd]);
            creaturesCountList.RemoveAt(curRnd);
        }

        CheckAndCreateEntities();

        if (generateConstantly)
        {
            StartCoroutine(CreateEntitiesCorut());
        }
    }
        private void GeneratePaths(Direction direction,
            AllowBearableMixStrategy allowBearable,
            MixStrategy strategy,
            UseExtendedMixes useExtendedMixes,
            IReadOnlyDictionary<string, Dictionary<string, Track>> excludedMixes,
            bool restrictArtistClumping,
            bool restrictGenreClumping,
            bool restrictTitleClumping,
            KeyMixStrategy keyMixStrategy,
            Track workingTrack,
            ICollection<string> availableTrackDescriptions,
            List<TrackPath> nextPaths,
            TrackPath currentPath)
        {
            var currentTrack = currentPath.Tracks.Last();

            DebugHelper.WriteLine("Start GeneratePaths " + currentTrack.Description);

            var excludeTrackDescriptions = GetDistinctTrackDescriptions(currentPath.Tracks);

            List<Track> mixTracks;
            if (strategy == MixStrategy.BestMix || strategy == MixStrategy.Variety ||
                strategy == MixStrategy.ExtraVariety)
            {
                mixTracks = GetBestMixTracks(currentTrack, currentPath.Tracks, allowBearable, availableTrackDescriptions,
                    excludeTrackDescriptions, restrictArtistClumping, restrictGenreClumping, restrictTitleClumping,
                    keyMixStrategy);
            }
            else if (strategy == MixStrategy.Unranked)
            {
                mixTracks = GetUnrankedTracks(currentTrack, currentPath.Tracks, availableTrackDescriptions,
                    excludeTrackDescriptions, keyMixStrategy, true);
            }
            else if (strategy == MixStrategy.Working)
            {
                mixTracks = GetWorkingTracks(currentTrack, currentPath.Tracks, workingTrack, availableTrackDescriptions,
                    excludeTrackDescriptions, keyMixStrategy);
            }
            else
            {
                mixTracks = new List<Track>();
            }

            if (direction != Direction.Any)
            {
                var preferredDirection = direction;
                if (preferredDirection == Direction.Cycle)
                    preferredDirection = GetPreferredDirection(currentTrack, currentPath.Tracks);

                var filteredTracks = FilterTracksByDirection(currentTrack, mixTracks, preferredDirection);
                if (filteredTracks.Count > 0) mixTracks = filteredTracks;
            }

            if ((strategy == MixStrategy.BestMix || strategy == MixStrategy.Variety ||
                 strategy == MixStrategy.ExtraVariety)
                && useExtendedMixes != UseExtendedMixes.Any)
            {
                mixTracks = FilterTracksByExtendedMix(currentTrack, mixTracks, useExtendedMixes);
            }

            if (excludedMixes != null)
            {
                mixTracks = FilterExcludedMixes(currentTrack, mixTracks, excludedMixes);
            }

            if (strategy == MixStrategy.BestMix || strategy == MixStrategy.Variety ||
                strategy == MixStrategy.ExtraVariety)
            {
                mixTracks = mixTracks
                    .OrderByDescending(x => GetAverageTrackAndMixAndKeyRank(currentTrack, x))
                    .ThenBy(x => x.Length)
                    .ToList();

                if (strategy == MixStrategy.Variety)
                {
                    mixTracks = FilterTracksForVariety(currentTrack, mixTracks);
                }
                else if (strategy == MixStrategy.ExtraVariety)
                {
                    mixTracks = FilterTracksForExtraVariety(currentTrack, mixTracks);
                }
            }

            var max = 3*Environment.ProcessorCount;
            mixTracks = mixTracks
                .Take(max)
                .ToList();

            var trackPaths = mixTracks.Select(mixTrack => new TrackPath(mixTrack, currentPath));
            foreach (var newPath in trackPaths)
            {
                lock (nextPaths)
                {
                    nextPaths.Add(newPath);
                    CalculateAverageRankForPath(newPath);
                }

                if (IsGenerationHalted()) break;
            }

            DebugHelper.WriteLine("End GeneratePaths " + currentTrack.Description);
        }