Beispiel #1
0
    public void ResetAgentPosition(CarAgent agent, bool randomize = false)
    {
        if (randomize)
        {
            agent.NextCheckpointIndex = Random.Range(0, Checkpoints.Count);
        }


        int previousCheckpointIndex = agent.NextCheckpointIndex - 1;

        if (previousCheckpointIndex == -1)
        {
            previousCheckpointIndex = Checkpoints.Count - 1;
        }

        float startPosition = racePath.FromPathNativeUnits(previousCheckpointIndex, CinemachinePathBase.PositionUnits.PathUnits);


        Vector3 basePosition = racePath.EvaluatePosition(startPosition);


        Quaternion orientation = racePath.EvaluateOrientation(startPosition);


        Vector3 positionOffset = Vector3.right * (CarAgents.IndexOf(agent) - CarAgents.Count / 2f)
                                 * UnityEngine.Random.Range(9f, 10f);


        agent.transform.position = basePosition + orientation * positionOffset;
        agent.transform.rotation = orientation;
    }
Beispiel #2
0
    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < _agentSpawnerDrawerManager.NumAgents; i++)
        {
            GameObject carObject = Instantiate(_carPrefab, transform.position, Quaternion.identity, transform);


            Material customMaterial = _agentSpawnerDrawerManager.MaterialsList[i];
            if (customMaterial != null && _agentSpawnerDrawerManager.UsingModel)
            {
                carObject.GetComponent <MeshRenderer>().material = customMaterial;
            }

            CarAgent carAgent    = carObject.GetComponent <CarAgent>();
            NNModel  customModel = _agentSpawnerDrawerManager.ModelsList[i];
            if (carAgent != null && customModel != null && _agentSpawnerDrawerManager.UsingModel)
            {
                LearningBrain customBrain = new LearningBrain();
                customBrain.brainParameters = carAgent.brain.brainParameters;
                customBrain.model           = customModel;
                carAgent.brain = customBrain;
                carObject.name = customBrain.model.name;
            }
        }
    }
    void Start()
    {
        // KM: We will stick to only BatMobil for our project
        int randomCar     = 0;
        int randomCarSpot = Random.Range(0, startPoints.Length);

        car = Instantiate(carPrefabs[randomCar], startPoints[randomCarSpot].transform.position, startPoints[randomCarSpot].transform.rotation);
        Instantiate(parkPrefabs[0], target.transform.position, target.transform.rotation);

        ParkControler.FindObjectOfType <ParkControler>().scene = SceneManager.GetActiveScene().name;

        goals = new List <Vector3>();
        if (SceneManager.GetActiveScene().name == "Scene_1")
        {
            CarAgent.FindObjectOfType <CarAgent>().isStun = true;
            CarAgent.FindObjectOfType <CarAgent>().setTarget(target);
            goals.Add(new Vector3(-11f, 0.3f, -5f));
            goals.Add(new Vector3(-3.2f, 0.3f, 12f));
            goals.Add(new Vector3(8f, 0.3f, 12f));
        }
        else if (SceneManager.GetActiveScene().name == "Scene_2")
        {
            CarAgentForLevel2.FindObjectOfType <CarAgentForLevel2>().isStun = true;
            CarAgentForLevel2.FindObjectOfType <CarAgentForLevel2>().setTarget(target);
            // goals.Add(new Vector3(-3.2f, 0.3f, 12f));
            // Points on storey 1
            //goals.Add(new Vector3(8f, 0.3f, 12f));
            // Points on storey 2
            goals.Add(new Vector3(78.42f, 0f, 12.24f));
        }
    }
Beispiel #4
0
    void OnTriggerEnter(Collider collider)
    {
        if (collider.transform.tag.ToLower() == "player" && !HasCarUsedIt)
        {
            agent = transform.parent.GetComponentInChildren <CarAgent>();

            if (goalType == GoalType.Milestone)
            {
                HasCarUsedIt = true;
                agent.GivePoints(goalReward);
            }
            else
            {
                // this will ensure the car tries to align when parking
                if (Mathf.Abs(agent.transform.rotation.y) <= goalMinRotation || !enforceGoalMinRotation)
                {
                    HasCarUsedIt = true;
                    agent.GivePoints(goalReward, true);
                }
                else
                {
                    agent.TakeAwayPoints();
                }
            }
        }
    }
 // Start is called before the first frame update
 void Start()
 {
     distanceSensorComponent = GetComponent<RayPerceptionSensorComponent3D>();
     // sensor = (RayPerceptionSensor)distanceSensorComponent.CreateSensor();
     agent = GetComponent<CarAgent>();
     resetCarStatus();
 }
    void Update()
    {
        ParkControler.FindObjectOfType <ParkControler>().scene = SceneManager.GetActiveScene().name;
        if (ParkControler.FindObjectOfType <ParkControler>().hasPark == true)
        {
            Destroy(car);
            int randomCar     = 0;
            int randomCarSpot = Random.Range(0, startPoints.Length);

            target.transform.position = getGoalLocation();
            car = Instantiate(carPrefabs[randomCar], startPoints[randomCarSpot].transform.position, startPoints[randomCarSpot].transform.rotation);
            Instantiate(parkPrefabs[0], target.transform.position, target.transform.rotation);

            if (SceneManager.GetActiveScene().name == "Scene_1")
            {
                CarAgent.FindObjectOfType <CarAgent>().isStun = true;
                CarAgent.FindObjectOfType <CarAgent>().setTarget(target);
            }
            else if (SceneManager.GetActiveScene().name == "Scene_2")
            {
                CarAgentForLevel2.FindObjectOfType <CarAgentForLevel2>().isStun = true;
                CarAgentForLevel2.FindObjectOfType <CarAgentForLevel2>().setTarget(target);
            }
            cameraFollow.FindObjectOfType <cameraFollow>().targets.RemoveAt(0);
        }
    }
Beispiel #7
0
    void InitializeCarAgentComponent()
    {
        CarAgent component = agent.GetComponent <CarAgent>();

        component.vertexPath    = this.road.pathCreator.path;
        component.startPosition = agent.transform.localPosition;
    }
Beispiel #8
0
    void Awake()
    {
        carAgent = GetComponentInChildren <CarAgent>();

        carAgent.onReset += DestroyAllSpawnedObjects;

        StartCoroutine(Spawn());
    }
Beispiel #9
0
    void ClearAgentAccident()
    {
        CarAgent carAgent = agent.GetComponent <CarAgent>();

        carAgent.windForce           = Vector3.zero;
        carAgent.ctrlXaxisMultiplier = 1.0f;
        carAgent.ctrlZaxisMultiplier = 1.0f;
    }
 public void StopFreeze()
 {
     if (SceneManager.GetActiveScene().name == "Scene_1")
     {
         CarAgent.FindObjectOfType <CarAgent>().isStun = false;
     }
     if (SceneManager.GetActiveScene().name == "Scene_2")
     {
         CarAgentForLevel2.FindObjectOfType <CarAgentForLevel2>().isStun = false;
     }
 }
Beispiel #11
0
 void OnCollisionStay(Collision collision)
 {
     if (collision.gameObject.tag == "Wall")
     {
         CarAgent agent = gameObject.GetComponent <CarAgent>();
         if (agent != null)
         {
             agent.AddReward(-10f);
         }
     }
 }
    /// <summary>
    /// Update the lap count of a given agent.
    /// </summary>
    /// <param name="carAgent">The agent to update it's lap count.</param>
    public void UpdateLapCount(CarAgent carAgent)
    {
        if (carAgent.isUser)
        {
            userLapCount.text = string.Format("LAP {0}/2", carAgent.LapsMade);
        }

        else
        {
            AILapCount.text = string.Format("LAP {0}/2", carAgent.LapsMade);
        }
    }
Beispiel #13
0
    void LossControlAccident()
    {
        if (!enableLossControlAccident)
        {
            return;
        }

        Debug.Log("LossControl happen !");
        CarAgent component = agent.GetComponent <CarAgent>();

        component.ctrlXaxisMultiplier = lossctrl_Xaxis_ratio;
        component.ctrlZaxisMultiplier = lossctrl_Zaxis_ratio;
    }
Beispiel #14
0
        public CarAgent CreateBarrier(bool opposite, float y)
        {
            int lane    = random.NextDouble() < 0.7 ? 0 : 1;
            var barrier = new CarAgent(_barrierModel, 90, laneWidth * 0.8f, 0.79f, opposite, GameObjectType.Roadblock, _gameStateProvider, null)
            {
                VY    = 0,
                MaxVY = 0,
                X     = GetLaneCenter(lane, opposite),
                Y     = y
            };

            return(barrier);
        }
Beispiel #15
0
    void OnTriggerEnter(Collider other)
    {
        //check if the player drove through this gate and we didn't yet add any points
        if (!other.gameObject.transform.root.CompareTag("Player") || addedScore)
        {
            return;
        }

        //increase the score by one and play some audio
        addedScore = true;
        manager.UpdateScore(1);
        scoreAudio.Play();
        CarAgent car = other.gameObject.GetComponent <CarAgent>();

        car?.PassGate();
    }
Beispiel #16
0
        public CarAgent CreateBusStop(bool opposite, float y)
        {
            int         lane    = 0;
            float       width   = 2f;
            const float height  = 2.77f;
            float       x       = GameConstants.RoadWidth / 2 + width / 2 + 0.1f;
            var         barrier = new CarAgent(_busStopModel, 270, width, height, opposite, GameObjectType.BusStop, _gameStateProvider, null)
            {
                VY    = 0,
                MaxVY = 0,
                X     = opposite ? -x : x,
                Y     = y
            };

            return(barrier);
        }
Beispiel #17
0
    void WindAccident()
    {
        if (!enableWindAccident)
        {
            return;
        }

        Debug.Log("WindAccident happen !");
        CarAgent component = agent.GetComponent <CarAgent>();
        Vector3  windForce = new Vector3();

        windForce.x         = wind_force_X;
        windForce.y         = (path_space == PathSpace.xz) ? 0.0f : wind_force_Y;
        windForce.z         = wind_force_Z;
        component.windForce = windForce;
    }
Beispiel #18
0
        private CarAgent CreateVehicleAgent(Model model, int lane, bool opposite, float y, float vanWidth, float height, float v, float rotation, IControlStrategy drivingStrategy = null)
        {
            if (drivingStrategy == null)
            {
                drivingStrategy = new OvertakingStrategy(v, lane, _gameStateProvider);
            }

            var van = new CarAgent(model, rotation, vanWidth, height, opposite, GameObjectType.Car, _gameStateProvider, drivingStrategy)
            {
                VY    = v,
                MaxVY = 100f / 3.6f,
                X     = GetLaneCenter(lane, opposite),
                Y     = y
            };

            return(van);
        }
Beispiel #19
0
    private void OnCollisionEnter(Collision collision)
    {
        //Debug.Log(collision.gameObject);

        if (collision.gameObject.tag == "Car")
        {
            Physics.IgnoreCollision(collision.collider, carCollider, true);
        }

        if (collision.gameObject.tag == "Wall")
        {
            CarAgent agent = gameObject.GetComponent <CarAgent>();
            if (agent != null)
            {
                agent.AddReward(-100);
                //agent.Done();
            }
        }
    }
Beispiel #20
0
    void SetupAgentConfiguration()
    {
        Rigidbody rigidbody = agent.GetComponent <Rigidbody>();

        rigidbody.mass = agent_mass;

        CarAgent carAgent = agent.GetComponent <CarAgent>();

        carAgent.xyz_mode        = (path_space == PathSpace.xyz);
        carAgent.forceMultiplier = force_multiplier;
        carAgent.tickerStart     = ticker_start;
        carAgent.tickerEnd       = ticker_end;
        carAgent.running_penalty = running_penalty;
        carAgent.failure_penalty = failure_penalty;

        carAgent.windForce           = Vector3.zero;
        carAgent.ctrlXaxisMultiplier = 1.0f;
        carAgent.ctrlZaxisMultiplier = 1.0f;
    }
Beispiel #21
0
    public void ResetCarAgent(CarAgent agent, Vector3 offset)
    {
        int prevCheckpointIndex = agent.NextCheckpointIndex - 1;

        if (prevCheckpointIndex == -1)
        {
            prevCheckpointIndex = 0;
        }

        float Startposition = racePath.FromPathNativeUnits(prevCheckpointIndex, CinemachinePathBase.PositionUnits.PathUnits);

        Vector3    basePosition   = racePath.EvaluatePosition(Startposition);
        Quaternion orientation    = racePath.EvaluateOrientation(Startposition);
        Vector3    offsetPosition = Vector3.right * (carAgents.IndexOf(agent) - carAgents.Count / 2f);

        //Debug.Log(offsetPosition);
        agent.transform.position = basePosition + orientation * offset;//offsetPosition;
        agent.transform.rotation = orientation;
    }
    /// <summary>
    /// Display the game over screen.
    /// </summary>
    /// <returns>
    /// Waits before displaying stats.
    /// </returns>
    /// <param name="user">The user agent.</param>
    /// <param name="AI">The AI agent.</param>
    public IEnumerator DisplayGameoverScreen(CarAgent user, CarAgent AI)
    {
        duringGameplay = false;

        // Wait 2 seconds before displaying the dark screen and the default game over text
        yield return(new WaitForSeconds(2));

        darkPanel.SetActive(true);
        gameoverDefaultText.SetActive(true);

        // Display the correct image according to the user winning status
        if (user.LapsMade > AI.LapsMade)
        {
            youWonImage.SetActive(true);
        }
        else
        {
            youLostImage.SetActive(true);
        }

        // Wait 1 second before displaying the game stat
        yield return(new WaitForSeconds(1));

        totalTime.text = raceTimer.GetTotalTime();
        totalTime.gameObject.SetActive(true);

        yield return(new WaitForSeconds(1));

        userLapsMade.text = string.Format("{0}/2", user.LapsMade);
        userLapsMade.gameObject.SetActive(true);

        yield return(new WaitForSeconds(1));

        AILapsMade.text = string.Format("{0}/2", AI.LapsMade);
        AILapsMade.gameObject.SetActive(true);

        // Wait 1 second and display the quit button
        yield return(new WaitForSeconds(1));

        quitButton.SetActive(true);
    }
Beispiel #23
0
    private void Update()
    {
        if (frames >= 500)
        {
            //Select target
            CarAgent highestVal = targets[0];

            foreach (CarAgent agent in targets)
            {
                if (highestVal.GetCumulativeReward() < agent.GetCumulativeReward())
                {
                    highestVal = agent;
                }
            }

            target = highestVal.transform.GetChild(3).transform;
        }
        else
        {
            frames++;
        }
    }
Beispiel #24
0
    void BreedNewAgents(List <CarAgent> prevAgents = null)
    {
        chromosomes.Clear();
        CarAgent   tempAgent    = null;
        CarAgent   newCarAgent  = null;
        Chromosome ch           = null;
        bool       isCleanAgent = false;

        for (int i = 0; i < populationSize; i++)
        {
            if (prevAgents != null && i < prevAgents.Count)
            {
                foreach (CarAgent agent in scaledCarPrefabs)
                {
                    if (agent.size == prevAgents[i].size)
                    {
                        newCarAgent  = agent;
                        isCleanAgent = false;
                        break;
                    }
                }
            }
            else
            {
                newCarAgent  = scaledCarPrefabs[UnityEngine.Random.Range(0, scaledCarPrefabs.Length)];
                isCleanAgent = true;
            }

            if (isCleanAgent)
            {
                ch    = new Chromosome();
                ch.id = id;
                id++;
            }
            else
            {
                ch = prevAgents[i].genes;
            }
            chromosomes.Add(ch);

            tempAgent         = Instantiate(newCarAgent, transform).GetComponent <CarAgent>();
            tempAgent.handler = this;

            road1Agents.Add(Instantiate(tempAgent, spawnPoint1.position + Vector3.forward * 25 * road1Agents.Count, Quaternion.Euler(0, 270, 0), spawnPoint1).GetComponent <CarAgent>());
            road1Agents[i].genes   = ch;
            road1Agents[i].handler = this;
            road1Agents[i].track   = 1;
            road1Agents[i].genes.SetGeneValue(GeneType.Size, newCarAgent.size);

            road2Agents.Add(Instantiate(tempAgent, spawnPoint2.position + Vector3.forward * 25 * road2Agents.Count, Quaternion.Euler(0, 270, 0), spawnPoint2).GetComponent <CarAgent>());
            road2Agents[i].genes   = ch;
            road2Agents[i].handler = this;
            road2Agents[i].track   = 2;
            road2Agents[i].genes.SetGeneValue(GeneType.Size, newCarAgent.size);

            road3Agents.Add(Instantiate(tempAgent, spawnPoint3.position + Vector3.forward * 25 * road3Agents.Count, Quaternion.Euler(0, 270, 0), spawnPoint3).GetComponent <CarAgent>());
            road3Agents[i].genes   = ch;
            road3Agents[i].handler = this;
            road3Agents[i].track   = 3;
            road3Agents[i].genes.SetGeneValue(GeneType.Size, newCarAgent.size);


            Destroy(tempAgent.gameObject);
            tempAgent = null;
            ch        = null;
        }
        CheckForDuplicates();
    }
Beispiel #25
0
 private void Start()
 {
     agent = GetComponent <CarAgent>();
 }
Beispiel #26
0
 public void UpdateTotalTime(CarAgent road1Agents)
 {
     currentTotalFitness.text = "Overall: " + (float)Math.Round((decimal)road1Agents.totalTimeAcrossTracks, 2) + " seconds";
 }
Beispiel #27
0
 void Awake()
 {
     // cache agent
     agent = transform.parent.parent.GetComponentInChildren <CarAgent>();
 }
 private void Awake()
 {
     instance = this;
 }
 public void AddPosition(CarAgent agent)
 {
     positions.Add(agent);
 }