// Upon triggering the checkpoint add points.
 private void OnTriggerEnter(Collider other)
 {
     // Check if the start checkpoint is hit first to avoid AI from learning to drive backwarks
     if (other.gameObject.tag == "start")
     {
         startPoint = true;
         net.AddFitness(5);
         // Set checkpoint false once achieved
         other.gameObject.SetActive(false);
         colliders.Add(other);
     }
     // Add points on triggering checkpoint
     if (other.gameObject.tag == "points" && startPoint)
     {
         net.AddFitness(5);
         // Set checkpoint false once achieved
         other.gameObject.SetActive(false);
         colliders.Add(other);
     }
     // Reset all the checkpoints once last checkpoint of lap is hit
     if (other.gameObject.tag == "end" && startPoint)
     {
         net.AddFitness(5);
         foreach (Collider collider in colliders)
         {
             collider.gameObject.SetActive(true);
         }
         colliders.Clear();
     }
 }
	public void UpdateInit()
	{
		if (MatchFinished) {
			StopGame();
			return; }
		ProcessNeuralOutput(Robot1, NetworkForRobot1);
		ProcessNeuralOutput(Robot2, NetworkForRobot2);

		if (Robot1.IsInContact && Robot1.IsAnyRobotSensorActivated())
		{
			BonusPointsForFirst += 0.01f;
		}
		if (Robot2.IsInContact && Robot2.IsAnyRobotSensorActivated())
		{
			BonusPointsForSecond += 0.01f;
		}

		if (CheckRobotDeath(Robot1))
		{
			NetworkForRobot2.AddFitness(1f + BonusPointsForSecond);
			NetworkForRobot1.AddFitness(-2f);
			MatchFinished = true;
		}
		else if (CheckRobotDeath(Robot2))
		{
			NetworkForRobot1.AddFitness(1f + BonusPointsForFirst);
			NetworkForRobot2.AddFitness(-2f);
			MatchFinished = true;
		}

		Robot1.RobotNameText.text = NetworkForRobot1.Name;
		Robot2.RobotNameText.text = NetworkForRobot2.Name;
	}
예제 #3
0
    void FixedUpdate()
    {
        if (initilized == true && !dead)
        {
            float[] inputs = new float[8];

            // Inputs
            inputs[0] = health;
            inputs[1] = currentAmmo;
            inputs[2] = Vector3.Distance(this.transform.position, player.position);

            float[] distanceClosestEnemies = clostFiveEnemies();
            inputs[3] = distanceClosestEnemies[0];
            inputs[4] = distanceClosestEnemies[1];
            inputs[5] = distanceClosestEnemies[2];
            inputs[6] = distanceClosestEnemies[3];
            inputs[7] = distanceClosestEnemies[4];

            // Outputs
            float[] output = net.FeedForward(inputs);

            float highestValue = output.Max();
            int   maxIndex     = output.ToList().IndexOf(highestValue);

            float outputvalue = output[maxIndex];
            switch (maxIndex)
            {
            case 0:     // Attack - Sh oot
                //int targetIndex = SelectTarget(outputvalue);
                //Transform target = clostestEnemies[targetIndex];
                Fire(player.transform);
                break;

            case 1:     // Hunt Enemy
                //lastAttackedEnemyIndex
                //float step = movementSpeed * Time.deltaTime;
                //this.transform.position = Vector3.MoveTowards(transform.position, player.position, step);
                break;

            case 2:     // Move towards player
                float step = movementSpeed * Time.deltaTime;
                this.transform.position = Vector3.MoveTowards(transform.position, player.position, step);
                break;

            case 3:     // Run
                break;

            case 4:     // Heal
                break;
            }

            // Fitness
            // Time alive Dis to player zombies killed
            //net.AddFitness(10);
            net.AddFitness(initdistance - Vector3.Distance(this.transform.position, player.position));
        }
    }
예제 #4
0
 void finish()
 {
     if (timer1 <= 20)
     {
         net.AddFitness(20 - timer1);
     }
     timer = 0;
     die();
 }
    void FixedUpdate()  //don't rename method
    {
        //distanceBackup = normalizedDistance; //ignore, for future stuff

        UpdateDistance();                                                                                       //updates all distance variables...

        if (initilized == true)                                                                                 //does the continuous calculation of movement etc. whilst simulation is running
        {
            DistanceDelay();                                                                                    //check distanceDelay Method for description

            ColorDistance();                                                                                    //fancy coloring

            float[] inputs = { changeInDistance1sec, changeInDistance2sec, normalizedDistancePlusNoise / 100 }; //inputs those three parameters into the neural net (distance/100 because trigger too strong otherwise, can be adjusted)
            float[] output = net.FeedForward(inputs);                                                           //'gives' the inputs to the neural net

            rBody.velocity        = 20f * transform.up;                                                         //velocity, can be adjusted through variable
            rBody.angularVelocity = 60000f * output[0];                                                         //angular velocity = constant (can be adjusted) * output of neural net

            net.AddFitness(normalizedDistance);                                                                 //fitnessfunction based on the distance. Could be changes to something else (like change in distance or so)


            //MonoBehaviour.print("fitnessadded: " +distance)
            //MonoBehaviour.print("fitnessadded");  (control print, ignore)
        }
    }
예제 #6
0
    void FixedUpdate()
    {
        if (_initialized)
        {
            float distance = Vector2.Distance(transform.position, hex.position); //distance to the HEX

            //Distance2Hex = distance;


            float[] inputs = new float[1];

            inputs[0] = BearingToHex() / 180; //-1 to +1

            float[] output = net.FeedForward(inputs);

            rBody.velocity        = 2.5f * transform.up;
            rBody.angularVelocity = 500f * output[0];

            //net.AddFitness((1f-Mathf.Abs(inputs[0])));   //the smaller the angle to the HEX the Fitter
            net.AddFitness((1f - distance));  //the closer to the HEX the Fitter

            if (distance > 20f)
            {
                distance = 20f;                 //max out distance to 20
            }
            foreach (Material t in mats)
            {
                t.color = new Color((1f - (distance / 20f)), 0, distance / 20f); //close is red, far is blue
            }
            // Manager.RemTimeSlider.value -= Time.deltaTime;
        }
    }
예제 #7
0
 // Update is called once per frame
 private void Update()
 {
     GetNeuralNetworkInputs();
     FormatNerualNetworkInputs();
     if (state == BirdState.Alive)
     {
         double[] inputs = new double[] { formattedVelocity, distanceToPipe, distanceToTop, distanceToBottom, distanceAboveGround };
         //if (Input.anyKeyDown)     // commented out to restrit user from controlling bird
         if (neuralNetwork.CalculateNextMove(inputs))
         {
             velocity += thrust;
             if (velocity > fallSpeed)
             {
                 velocity = fallSpeed;
             }
         }
         gameObject.transform.position = new Vector3(0, transform.position.y + (float)velocity, 0);
         if (velocity >= -fallSpeed)
         {
             velocity -= acceleration;
         }
         if (velocity < -fallSpeed)
         {
             velocity = -fallSpeed;
         }
         neuralNetwork.AddFitness(1);
     }
     else if (state == BirdState.Dead && transform.position.x > -3.7)
     {
         transform.position = new Vector3(transform.position.x - speed, transform.position.y, 0);
     }
 }
예제 #8
0
    void FixedUpdate()
    {
        if (initilized == true)
        {
            float distance = Vector3.Distance(transform.position, pickup.position);
            if (distance > 20f)
            {
                distance = 20f;
            }
            for (int i = 0; i < mats.Length; i++)
            {
                mats[i].color = new Color(distance / 20f, (1f - (distance / 20f)), (1f - (distance / 20f)));
            }

            Vector3 deltaVector = (pickup.position - transform.position);
            float[] inputs      = new float[6];
            inputs[0] = deltaVector.x;
            inputs[1] = deltaVector.z;
            inputs[2] = rBody.velocity.x;
            inputs[3] = rBody.velocity.z;
            inputs[4] = pickup.position.x;
            inputs[5] = pickup.position.z;
            //inputs[2] = transform.position.x;
            //inputs[3] = transform.position.z;

            float[] output = net.FeedForward(inputs);

            Vector3 movement = new Vector3(output[0], 0, output[1]);
            // rBody.velocity = new Vector3(movement.x * 16, 0, movement.z * 16);
            rBody.AddForce(movement * 24);

            net.AddFitness((5f - Mathf.Abs(deltaVector.magnitude)));
        }
    }
예제 #9
0
    // Update is called once per frame
    void FixedUpdate()
    {
        if (isAlive)
        {
            //SOME AMOUNT OF RAYCASTED POINTS
            float[] inputs = new float[5];

            for (int i = 0; i < 5; i++)
            {
                inputs[i] = sensors[i].output;
            }



            //FEED THEM FORWARD
            float[] outputs = net.FeedForward(inputs);



            //APPLY OUTPUTS: 0 is speed, 1 is rotation
            rBody.velocity = outputs[0] * CAR_SPEED * transform.up;

            rBody.angularVelocity = outputs[1] * ROTATION_SPEED;


            //UPDATE FITNESS OF CAR
            net.AddFitness(rBody.velocity.magnitude * Time.deltaTime);
        }
    }
예제 #10
0
 private void OnTriggerEnter(Collider other)
 {
     if (other.gameObject.CompareTag("Bunny"))
     {
         net.AddFitness(100f);
         canmove = false;
         Invoke("Timer", 1.8f);
     }
 }
예제 #11
0
    void FixedUpdate()
    {
        if (initilized == true)
        {
            // Angle Calculation, input 0
            // distance isnt used for anything currently
            //  float distance = Vector3.Distance(transform.position, target.position);
            float[] inputs = new float[1];
            // orig
            float angle = transform.eulerAngles.y % 360f - 90;
            if (angle < 0f)
            {
                angle += 360f;
            }
            Vector3 deltaVector = (target.position - transform.position).normalized;
            float   rad         = Mathf.Atan2(deltaVector.x, deltaVector.z);
            rad *= Mathf.Rad2Deg;
            // rad represents the angle of the line between the bot and the target in degrees
            rad = rad % 360;
            if (rad < 0)
            {
                rad = 360 + rad;
            }
            // rad is a value between 0 and 359
            rad = 90f - rad;
            if (rad < 0f)
            {
                rad += 360f;
            }
            rad  = 360 - rad;
            rad -= angle;
            if (rad < 0)
            {
                rad = 360 + rad;
            }
            if (rad >= 180f)
            {
                rad  = 360 - rad;
                rad *= -1f;
            }
            rad *= Mathf.Deg2Rad;
            // END OF INPUT 0
            inputs[0] = rad / (Mathf.PI);

            float[] output = net.FeedForward(inputs);

            //controller.SimpleMove(controller.transform.forward * speed);
            //controller.transform.Rotate(0, output[0]*RotationalSpeed, 0);

            rb.velocity        = 2.5f * transform.forward;
            rb.angularVelocity = new Vector3(0f, 500f * output[0], 0f);

            //net.AddFitness(distanceToTarget-distance);
            //distanceToTarget = distance;
            net.AddFitness(1f - Mathf.Abs(inputs[0]));
        }
    }
예제 #12
0
 /// <summary>
 /// checks for collsions
 /// </summary>
 /// <param name="col">Col.</param>
 void OnCollisionEnter2D(Collision2D col)
 {
     //if the herbivore collides with herbivore
     if (col.gameObject.tag == "Herbivore")
     {
         //eat the food and delete the food object
         net.AddFitness(8f);
         col.gameObject.GetComponent <HerbivoreManager> ().getNet().AddFitness(-4f);
     }
 }
예제 #13
0
 /// <summary>
 /// checks for collsions
 /// </summary>
 /// <param name="col">Col.</param>
 void OnTriggerEnter2D(Collider2D col)
 {
     //if the herbivore collides with food
     if (col.gameObject.tag == "Food")
     {
         //eat the food and delete the food object
         net.AddFitness(6f);
         foodManager.foods.Remove(col.gameObject);
         Destroy(col.gameObject);
     }
 }
예제 #14
0
    void FixedUpdate()
    {
        if (initialized == true)
        {
            float[] inputs = new float[1];


            float angle = transform.eulerAngles.z % 360f;
            if (angle < 0f)
            {
                angle += 360f;
            }

            Vector2 deltaVector = (hex.position - transform.position).normalized;


            float rad = Mathf.Atan2(deltaVector.y, deltaVector.x);
            rad *= Mathf.Rad2Deg;

            rad = rad % 360;
            if (rad < 0)
            {
                rad = 360 + rad;
            }

            rad = 90f - rad;
            if (rad < 0f)
            {
                rad += 360f;
            }
            rad  = 360 - rad;
            rad -= angle;
            if (rad < 0)
            {
                rad = 360 + rad;
            }
            if (rad >= 180f)
            {
                rad  = 360 - rad;
                rad *= -1f;
            }
            rad *= Mathf.Deg2Rad;

            inputs[0] = rad / (Mathf.PI);


            float[] output = net.FeedForward(inputs);

            rBody.velocity        = 2.5f * transform.up;
            rBody.angularVelocity = 500f * output[0];

            net.AddFitness((1f - Mathf.Abs(inputs[0])));
        }
    }
예제 #15
0
    void FixedUpdate()
    {
        if (initialized)
        {
            float   distance = Vector2.Distance(transform.position, target.position);
            float[] inputs   = new float[1];
            float   angle    = transform.eulerAngles.z % 360f;

            if (angle < 0f)
            {
                angle += 360f;
            }

            Vector2 deltaVector = (target.position - transform.position).normalized;
            float   rad         = Mathf.Atan2(deltaVector.y, deltaVector.x);
            rad *= Mathf.Rad2Deg;
            rad  = rad % 360;

            if (rad < 0)
            {
                rad = 360 + rad;
            }

            rad = 90f - rad;

            if (rad < 0f)
            {
                rad += 360f;
            }

            rad  = 360 - rad;
            rad -= angle;

            if (rad < 0)
            {
                rad = 360 + rad;
            }

            if (rad >= 180f)
            {
                rad  = 360 - rad;
                rad *= -1f;
            }

            rad      *= Mathf.Deg2Rad;
            inputs[0] = rad / (Random.Range(1, 100));
            float[] output = brain.FeedForward(inputs);
            self.velocity        = 8f * transform.up;
            self.angularVelocity = 1000f * output[0];
            brain.AddFitness((1f - Mathf.Abs(inputs[0])));
        }
    }
    void Update()
    {
        if (initialised)
        {
            float[] inputs = new float[INPUTS_ARRAY_LENGTH];

            float angle = transform.eulerAngles.z % 360;

            if (angle < 0f)
            {
                angle += 360f;
            }

            Vector2 vectorToPlayer = (player.position - transform.position);

            float degrees = Mathf.Atan2(vectorToPlayer.y, vectorToPlayer.x) * Mathf.Rad2Deg;

            degrees %= 360;

            if (degrees < 90f)
            {
                degrees += 360f;
            }

            degrees = 360 - degrees;

            degrees -= angle;

            if (degrees < 0f)
            {
                degrees += 360;
            }

            if (degrees >= 180f)
            {
                degrees  = 360 - degrees;
                degrees *= -1f;
            }

            float radians = degrees * Mathf.Deg2Rad;

            inputs[0] = radians / Mathf.PI;

            float[] output = network.CalculateValues(inputs);

            rocketBody.velocity        = 2.5f * transform.up;
            rocketBody.angularVelocity = 500f * output[0];

            network.AddFitness(1f - Mathf.Abs(inputs[0]));
        }
    }
예제 #17
0
    private void FixedUpdate()
    {
        if (initialized == true)
        {
            if (FreeRun == false && Break == false)
            {
                GetComponent <Rigidbody>().AddForce(transform.right * acceleration, ForceMode.VelocityChange);
                GetComponent <Rigidbody>().useGravity = true;
            }
            //Break
            if (Break == true)
            {
                GetComponent <Rigidbody>().AddForce(-transform.right * breakForce, ForceMode.VelocityChange);
                GetComponent <Rigidbody>().useGravity = true;
                inputs[0] = breakForce;
            }

            //float distance = Vector3.Distance(rBody.position, Stoßplatte.position);
            //if (distance <= 50f)
            //{
            //    print("angekommen");
            //    //Fehlerbehaftet
            //}



            //Aus Update Möglicherweise übernehmen



            float[] outputs = net.FeedForward(inputs);      //speichert vorhergehendes Ergebnis

            net.AddFitness((1f - Mathf.Abs(inputs[0])));    //Fitness zwischen 0 - 1

            Init(net);
        }
    }
예제 #18
0
    public void UpdateDelta(float deltatime)
    {
        Vector3 deltaVector       = _target - _position;
        float   magnitude         = deltaVector.magnitude;
        Vector3 directionToTarget = deltaVector / magnitude;
        Vector3 direction         = new Vector3(Mathf.Cos(_rotation * Mathf.Deg2Rad), Mathf.Sin(_rotation * Mathf.Deg2Rad), 0f);

        float normalizedDistanceInv = 1f - Mathf.Min(magnitude, maxDistance) / maxDistance;                        // 0 ... 1
        float angleToTarget         = Vector3.SignedAngle(direction, directionToTarget, new Vector3(0f, 0f, -1f)); //-180 ... 180
        float normalizedAngle       = angleToTarget / 180f;                                                        // -1 ... 1

        var leftAngle  = -Mathf.Min(normalizedAngle, 0f);                                                          // -1 .. 0 -> 0 ... 1
        var rightAngle = Mathf.Max(normalizedAngle, 0f);                                                           // 0 .. 1 -> 0 ... 1

        List <float> output;

        if (net != null)
        {
            var inputs = new List <float>
            {
                normalizedDistanceInv,
                rightAngle,
                leftAngle
            };
            net.FeedForward(inputs);
            output = net.GetResults();
            float fitness = normalizedDistanceInv * 2f;
            net.AddFitness(fitness * fitness * fitness);
        }
        else if (Manual)
        {
            output = new List <float>
            {
                Input.GetKey(KeyCode.W) ? 1f : 0f,
                Input.GetKey(KeyCode.D) ? 1f : 0f,
                Input.GetKey(KeyCode.A) ? 1f : 0f
            };
        }
        else
        {
            output = new List <float>
            {
                //normalizedDistanceInv < 0.99f ? 1f : 0f,
                rightAngle > 0.05f ? 1f : 0f,
                leftAngle > 0.05f ? 1f : 0f
            };
        }
        float moveRight = output[0];
        float moveLeft  = output[1];

        float speed = 10f;

        float rotation = 0f;

        if (moveRight > .9f)
        {
            rotation -= 90f;
        }
        if (moveLeft > .9f)
        {
            rotation += 90f;
        }

        _rotation += rotation * deltatime;
        _position += direction * speed * deltatime;

        _position.x = Mathf.Clamp(_position.x, 0f, maxDistance);
        _position.y = Mathf.Clamp(_position.y, 0f, maxDistance);
        if (_rotation < 0f)
        {
            _rotation += 360f;
        }
        if (_rotation > 360f)
        {
            _rotation -= 360f;
        }

        elapsed = Mathf.Min(elapsed + deltatime, lifetime);
    }
예제 #19
0
    void FixedUpdate()
    {
        if (initialized == true)
        {
            float[] inputs  = new float[1];
            float   dist    = Vector2.Distance(transform.position, player.position);
            float   angle   = transform.eulerAngles.z % 360.0f;
            Vector2 dVector = (player.position - transform.position).normalized;
            float   rad     = Mathf.Atan2(dVector.y, dVector.x);

            if (dist > 20.0f)
            {
                dist = 20.0f;
            }
            if (angle < 0.0f)
            {
                angle += 360.0f;
            }

            for (int i = 0; i < mats.Length; i++)
            {
                mats[i].color = new Color(dist / 20.0f, (1.0f - (dist / 20.0f)), (1.0f - (dist / 20.0f)));
            }

            rad *= Mathf.Rad2Deg;

            rad %= 360.0f;
            if (rad < 0.0f)
            {
                rad += 360.0f;
            }

            rad = 90.0f - rad;
            if (rad < 0.0f)
            {
                rad += 360.0f;
            }

            rad  = 360.0f - rad;
            rad -= angle;
            if (rad < 0.0f)
            {
                rad += 360.0f;
            }

            if (rad >= 180.0f)
            {
                rad  = 360.0f - rad;
                rad *= -1.0f;
            }

            rad       *= Mathf.Deg2Rad;
            inputs [0] = rad / (Mathf.PI);

            float[] output = neurNet.FeedForward(inputs);

            ridBody.velocity        = 2.5f * transform.up;
            ridBody.angularVelocity = 500.0f * output[0];

            neurNet.AddFitness(1.0f - Mathf.Abs(inputs [0]));
        }
    }
예제 #20
0
    private void AIMovement()
    {
        if (gameMaster.wipeOut) //when area resets
        {
            score     = 0;
            isAlife   = true;
            inputs[0] = 0f;
            inputs[1] = 0f;
            inputs[2] = 0f;
            inputs[3] = 0f;
            inputs[4] = 0f;
            gameMaster.statusButton[myID].GetComponentInChildren <Text>().color = Color.green;
            net = gameMaster.GiveNetworkByID(myID);             //getting network of the next generation with same ID
            gameObject.layer   = 0;                             //making hero touchable to enemies again
            transform.position = spawnpoint.transform.position; //moving hero to fixed reload position
        }
        if (score >= 600)
        {
            //after 10 minutes of survival, game is ended
            isAlife = false;
            EndGame();
        }
        if (isAlife & pflTimeStamp < Time.time)
        {
            //--adding fitness every second--
            score++;
            net.AddFitness(1.0f);
            pflTimeStamp = Time.time + pointForLivingCooldown;
            gameMaster.statusButton[myID].GetComponentInChildren <Text>().text = score.ToString();
        }
        //first input: position y of hero, normalized
        inputs[0] = Mathf.InverseLerp(spawnpoint.transform.position.y - 5f, spawnpoint.transform.position.y + 4.5f, transform.position.y);
        GameObject closest  = FindClosestEnemy("Enemy");
        GameObject closest1 = FindClosestEnemy("Enemyblt");

        if (closest != null)
        {
            //relative position on x and y axis of closest enemy ship, normalized
            inputs[1] = Mathf.Clamp(closest.transform.position.x - transform.position.x, -20, 20) / 20;
            inputs[2] = Mathf.Clamp(closest.transform.position.y - transform.position.y, -10, 10) / 10;
        }
        else
        {
            //if no enemies found
            inputs[1] = 1;
            inputs[2] = 1;
        }
        if (closest1 != null)
        {
            //relative position on x and y axis of closest enemy bullet, normalized
            inputs[3] = Mathf.Clamp(closest1.transform.position.x - transform.position.x, -20, 20) / 20;
            inputs[4] = Mathf.Clamp(closest1.transform.position.y - transform.position.y, -10, 10) / 10;
        }
        else
        {
            //if no enemy bullets found
            inputs[3] = 1;
            inputs[4] = 1;
        }
        outputs = net.FeedForward(inputs); //calculating outputs with fresh inputs
        if (outputs[0] > sensitivity)      //moving up when firts output has value>0
        {
            GetComponent <Rigidbody2D>().velocity = Vector2.up * speed * Time.deltaTime;
        }
        if (outputs[1] > sensitivity)//moving down when second output has value>0
        {
            GetComponent <Rigidbody2D>().velocity = Vector2.down * speed * Time.deltaTime;
        }
        if (outputs[0] < sensitivity && outputs[1] < sensitivity) //stopping moving when both outputs are lower than 0
        {
            GetComponent <Rigidbody2D>().velocity = Vector2.zero;
        }
    }
예제 #21
0
    void FixedUpdate()
    {
        // If we started
        if (initilized == true)
        {
            // Get distance
            float distance = Vector2.Distance(transform.position, hex.position);

            // If our distance is greater than 20
            // Set it to 20
            if (distance > 20f)
            {
                distance = 20f;
            }

            // Change the color
            for (int i = 0; i < mats.Length; i++)
            {
                mats[i].color = new Color(distance / 20f, (1f - (distance / 20f)), (1f - (distance / 20f)));
            }

            float[] inputs = new float[1];


            float angle = transform.eulerAngles.z % 360f;
            if (angle < 0f)
            {
                angle += 360f;
            }


            Vector2 deltaVector = (hex.position - transform.position).normalized;


            float rad = Mathf.Atan2(deltaVector.y, deltaVector.x);
            rad *= Mathf.Rad2Deg;

            rad = rad % 360;
            if (rad < 0)
            {
                rad = 360 + rad;
            }

            rad = 90f - rad;
            if (rad < 0f)
            {
                rad += 360f;
            }
            rad  = 360 - rad;
            rad -= angle;
            if (rad < 0)
            {
                rad = 360 + rad;
            }
            if (rad >= 180f)
            {
                rad  = 360 - rad;
                rad *= -1f;
            }
            rad *= Mathf.Deg2Rad;

            inputs[0] = rad / (Mathf.PI);


            // Create a new float array and set it to the result of FeedForward
            float[] output = net.FeedForward(inputs);
            // Set the velocity forward
            rBody.velocity = 3 * transform.up;
            //Set the angular velocity, this determines rotation
            rBody.angularVelocity = 500f * output[0];
            // Add fitness
            net.AddFitness((1f - Mathf.Abs(inputs[0])));
        }
    }
예제 #22
0
    void FixedUpdate()
    {
        if (initilized == true && !dead)
        {
            float distance = Vector3.Distance(this.transform.position, player.position);

            //for (int i = 0; i < mats.Length; i++)
            //    mats[i].color = new Color(distance / 20f, (1f - (distance / 20f)), (1f - (distance / 20f)));

            float[] inputs = new float[7];

            // Dir
            // Gets a vector that points from the player's position to the target's.
            var heading = player.position - gameObject.transform.position;

            var distance2 = heading.magnitude;
            var direction = heading / distance; // This is now the normalized direction.

            // Set up a raycast hit for knowing what we hit
            RaycastHit hit;

            // Set up out 5 feelers for undertanding the world
            Vector3[] feeler = new Vector3[]
            {
                // 0 = L
                transform.TransformDirection(Vector3.left),
                // 1 - FL
                transform.TransformDirection(Vector3.left + Vector3.forward),
                // 2 - F
                transform.TransformDirection(Vector3.forward),
                // 3 = FR
                transform.TransformDirection(Vector3.right + Vector3.forward),
                // 4 = R
                transform.TransformDirection(Vector3.right),
            };

            // Use this to collect all feeler distances, then well pass them through our NN for an output
            inp = new float[feeler.Length];

            // Loop through all feelers
            for (int i = 0; i < feeler.Length; i++)
            {
                // See what all feelers feel
                if (Physics.Raycast(transform.position, feeler[i], out hit))
                {
                    // If feelers feel something other than Forrest & nothing
                    if (hit.collider != null && hit.collider != col)
                    {
                        if (hit.collider.tag == "Environment")
                        {
                            // Set the input[i] to be the distance of feeler[i]
                            inp[i] = hit.distance;
                        }
                    }
                }

                //if (inp[i] > 0)
                //    Debug.DrawRay(transform.position, feeler[i] * 10, Color.green);
                //else
                // Draw the feelers in the Scene mode
                Debug.DrawRay(transform.position, feeler[i] * 10, Color.red);
            }

            inputs[0] = direction.x;
            inputs[1] = direction.z;
            inputs[2] = inp[0];
            inputs[3] = inp[1];
            inputs[4] = inp[2];
            inputs[5] = inp[3];
            inputs[6] = inp[4];

            debugInputs[0] = direction.x;
            debugInputs[1] = direction.z;
            debugInputs[2] = inp[0];
            debugInputs[3] = inp[1];
            debugInputs[4] = inp[2];
            debugInputs[5] = inp[3];
            debugInputs[6] = inp[4];

            float[] output = net.FeedForward(inputs);

            rBody.velocity = movementSpeed * transform.forward;

            Vector3 av = new Vector3();
            av.y = 500f * output[0]; //500
            rBody.angularVelocity = av;

            //Vector3 rot = new Vector3();
            //rot.y = output[0] * 360;
            //this.transform.Rotate(rot);

            // Fitness
            net.AddFitness(initdistance - distance);
        }
    }
예제 #23
0
    void FixedUpdate()
    {
        if (initilized == true)
        {
            float distance = Vector2.Distance(transform.position, hex.position);
            if (distance > 20f)
            {
                distance = 20f;
            }
            for (int i = 0; i < mats.Length; i++)
            {
                mats[i].color = new Color(distance / 20f, (1f - (distance / 20f)), (1f - (distance / 20f)));
            }

            float[] inputs = new float[1];


            float angle = transform.eulerAngles.z % 360f;
            if (angle < 0f)
            {
                angle += 360f;
            }

            Vector2 deltaVector = (hex.position - transform.position).normalized;


            float rad = Mathf.Atan2(deltaVector.y, deltaVector.x);
            rad *= Mathf.Rad2Deg;

            rad = rad % 360;
            if (rad < 0)
            {
                rad = 360 + rad;
            }

            rad = 90f - rad;
            if (rad < 0f)
            {
                rad += 360f;
            }
            rad  = 360 - rad;
            rad -= angle;
            if (rad < 0)
            {
                rad = 360 + rad;
            }
            if (rad >= 180f)
            {
                rad  = 360 - rad;
                rad *= -1f;
            }
            rad *= Mathf.Deg2Rad;

            inputs[0] = rad / (Mathf.PI);


            float[] output = net.FeedForward(inputs);

            rBody.velocity        = 2.5f * transform.up;
            rBody.angularVelocity = 500f * output[0];

            net.AddFitness((1f - Mathf.Abs(inputs[0])));
        }
    }
예제 #24
0
    void Update()
    {
        sensorTOP.GetComponent <LineRenderer> ().SetPosition(0, sensorTOP.transform.position);
        sensorTOP.GetComponent <LineRenderer> ().SetPosition(1, sensorTOP.transform.position);

        sensorBOTTOM.GetComponent <LineRenderer> ().SetPosition(0, sensorBOTTOM.transform.position);
        sensorBOTTOM.GetComponent <LineRenderer> ().SetPosition(1, sensorBOTTOM.transform.position);

        sensorRıGHT.GetComponent <LineRenderer> ().SetPosition(0, sensorRıGHT.transform.position);
        sensorRıGHT.GetComponent <LineRenderer> ().SetPosition(1, sensorRıGHT.transform.position);

        sensorLEFT.GetComponent <LineRenderer> ().SetPosition(0, sensorLEFT.transform.position);
        sensorLEFT.GetComponent <LineRenderer> ().SetPosition(1, sensorLEFT.transform.position);

        //, LayerMask.NameToLayer("Wall")
        RaycastHit2D hitTOP = Physics2D.Raycast(sensorTOP.transform.position, Vector2.up, maxDistance, LayerMask.NameToLayer("Wall"));

        if (hitTOP.collider != null)
        {
            distanceTOP = Mathf.Abs(hitTOP.point.y - transform.position.y);

            sensorTOP.GetComponent <LineRenderer> ().SetPosition(1, hitTOP.point);
        }
        else
        {
            distanceTOP = maxDistance;
        }

        RaycastHit2D hitBOTTOM = Physics2D.Raycast(sensorBOTTOM.transform.position, Vector2.down, maxDistance, LayerMask.NameToLayer("Wall"));

        if (hitBOTTOM.collider != null)
        {
            distanceBOTTOM = Mathf.Abs(hitBOTTOM.point.y - transform.position.y);

            sensorBOTTOM.GetComponent <LineRenderer> ().SetPosition(1, hitBOTTOM.point);
        }
        else
        {
            distanceBOTTOM = maxDistance;
        }

        RaycastHit2D hitRıGHT = Physics2D.Raycast(sensorRıGHT.transform.position, Vector2.right, maxDistance, LayerMask.NameToLayer("Wall"));

        if (hitRıGHT.collider != null)
        {
            distanceRıGHT = Mathf.Abs(hitRıGHT.point.x - transform.position.x);

            sensorRıGHT.GetComponent <LineRenderer> ().SetPosition(1, hitRıGHT.point);
        }
        else
        {
            distanceRıGHT = maxDistance;
        }

        RaycastHit2D hitLEFT = Physics2D.Raycast(sensorLEFT.transform.position, Vector2.left, maxDistance, LayerMask.NameToLayer("Wall"));

        if (hitLEFT.collider != null)
        {
            distanceLEFT = Mathf.Abs(hitLEFT.point.x - transform.position.x);

            sensorLEFT.GetComponent <LineRenderer> ().SetPosition(1, hitLEFT.point);
        }
        else
        {
            distanceLEFT = maxDistance;
        }

        inputs  = new float[] { distanceTOP * 1 / maxDistance, distanceBOTTOM * 1 / maxDistance, distanceRıGHT * 1 / maxDistance, distanceLEFT * 1 / maxDistance };
        outputs = network.FeedForward(inputs);

        Vector2 velocity = Vector2.zero;

        if (outputs [0] > 0f)
        {
            velocity += speed * Vector2.up;
        }
        else
        {
            velocity += speed * Vector2.down;
        }
        if (outputs [1] > 0f)
        {
            velocity += speed * Vector2.left;
        }
        else
        {
            velocity += speed * Vector2.right;
        }

        if (!isGod)
        {
            transform.position = new Vector3(transform.position.x + (velocity.x * Time.deltaTime), transform.position.y + (velocity.y * Time.deltaTime), 0f);
        }
        network.AddFitness(0.1f);
        fitness = network.GetFitness();

        if (fitness > GameObject.FindGameObjectWithTag("Manager").GetComponent <Manager> ().highestFitness)
        {
            GameObject.FindGameObjectWithTag("Manager").GetComponent <Manager> ().highestFitness = fitness;
            GameObject.FindGameObjectWithTag("Manager").GetComponent <Manager> ().bestNetwork    = this.network;
            GetComponent <SpriteRenderer> ().color = Color.yellow;
        }
        else
        {
            GetComponent <SpriteRenderer> ().color = Color.green;
        }


        //if (fitness >= GameObject.FindGameObjectWithTag ("Manager").GetComponent<Manager> ().fitnessLimit)
        //Destroy ();
    }
예제 #25
0
 public void OnCheckPoint()
 {
     _net.AddFitness(1);
 }
    void FixedUpdate()
    {
        if (initilized == true)
        {
            // Every 10 updates, check to see if the bot has made progress
            if (ticks % 10 == 0)
            {
                if (Mathf.Abs(transform.position.x - prevPos.x) < minimumBotSpeed)
                {
                    destroyBot();
                }
                else
                {
                    prevPos = transform.position;
                }
            }

            // Find all the gronud platforms and enemies (expensvie)
            GameObject[] platforms = GameObject.FindGameObjectsWithTag("Ground");
            GameObject[] enemies   = GameObject.FindGameObjectsWithTag("Enemy");

            // Make a list for all platform positions relative to themselves
            List <float> positions = new List <float> ();

            // Add each x and y position to the input array
            for (int i = 0; i < platforms.Length; i++)
            {
                positions.Add(transform.position.x - platforms [i].transform.position.x);
                positions.Add(transform.position.y - platforms [i].transform.position.y);
            }

            // Check to see if there are enemies.  Add them.
            if (enemies != null)
            {
                for (int i = 0; i < enemies.Length; i++)
                {
                    positions.Add(transform.position.x - enemies [i].transform.position.x);
                    positions.Add(transform.position.y - enemies [i].transform.position.y);
                }
            }


            // Get the output from the network and set the move and jump values
            float[] output = net.FeedForward(positions.ToArray());
            float   xMove  = output [0];
            float   jump   = output [1];
            if (jump > 0.5)
            {
                jumpDown = true;
            }
            else
            {
                jumpDown = false;
            }


            // Move the player left or right based on the first output
            rb.velocity = new Vector2(xMove * botSpeed * Time.deltaTime, rb.velocity.y);

            // Determine if the player should jump based on the second output
            if (jumpDown && Grounded())
            {
                StartCoroutine("JumpCurve");
            }

            // Bot fitness is based on how far right it makes it in the level
            net.AddFitness(transform.position.x);
        }

        // Destroy the bot if it falls off the platform
        if (transform.position.y < 0)
        {
            destroyBot();
        }

        ticks++;
    }