66 lines
2.2 KiB
C#
66 lines
2.2 KiB
C#
using UnityEngine;
|
|
|
|
public class Agent : MonoBehaviour {
|
|
private const float Speed = 1.0f;
|
|
private const float RotationSpeed = 1.0f;
|
|
|
|
public NeuralNetwork Network;
|
|
private Transform _target;
|
|
private bool _initialized = false;
|
|
|
|
public void Initialize(Transform target, in NeuralNetwork network) {
|
|
_target = target;
|
|
|
|
if (network != null)
|
|
Network = new NeuralNetwork(network);
|
|
else
|
|
Network = new NeuralNetwork(new [] { 5, 4, 3, 1 });
|
|
|
|
Network.Mutate();
|
|
_initialized = true;
|
|
}
|
|
|
|
private void Update() {
|
|
/*float angle = Mathf.Atan2(transform.position.y - _target.position.y, transform.position.x - _target.position.x);
|
|
|
|
float rotateAngle = Network.FeedForward(new []{ angle })[0] * Mathf.Deg2Rad;
|
|
|
|
transform.Rotate(0, 0, rotateAngle);
|
|
|
|
angle = Mathf.Atan2(transform.position.y - _target.position.y, transform.position.x - _target.position.x);
|
|
|
|
float score = Mathf.Cos(angle);
|
|
Network.SetScore(score);
|
|
|
|
transform.Translate(transform.right * Time.deltaTime * Speed);
|
|
|
|
transform.position = new Vector2(Mathf.Clamp(transform.position.x, -10, 10), Mathf.Clamp(transform.position.y, -5, 5));*/
|
|
|
|
if (!_initialized) return;
|
|
|
|
Vector2 direction = _target.position - transform.position;
|
|
float angle = Mathf.Atan2(direction.y, direction.x);
|
|
|
|
float[] output = Network.FeedForward(new [] {
|
|
angle,
|
|
transform.position.x,
|
|
transform.position.y,
|
|
_target.position.x,
|
|
_target.position.y
|
|
});
|
|
|
|
transform.Rotate(0, 0, output[0] * Time.deltaTime * RotationSpeed);
|
|
transform.Translate(transform.right * Time.deltaTime * Speed);
|
|
|
|
transform.position = new Vector2(Mathf.Clamp(transform.position.x, -10, 10), Mathf.Clamp(transform.position.y, -5, 5));
|
|
|
|
Network.SetScore(CalculateScore());
|
|
}
|
|
|
|
private float CalculateScore() {
|
|
|
|
float distance = Vector2.Distance(transform.position, _target.position);
|
|
|
|
return -distance;
|
|
}
|
|
} |