59 lines
1.4 KiB
C#
59 lines
1.4 KiB
C#
using UnityEngine;
|
|
|
|
public class Boomerang : MonoBehaviour {
|
|
|
|
private bool _initialized;
|
|
private Transform _target;
|
|
|
|
private NeuralNetwork _network;
|
|
private Rigidbody2D _rigidbody;
|
|
|
|
public void Initialize(NeuralNetwork network, Transform target) {
|
|
_network = network;
|
|
_target = target;
|
|
_initialized = true;
|
|
}
|
|
|
|
private void Start() {
|
|
_rigidbody = GetComponent<Rigidbody2D>();
|
|
}
|
|
|
|
private void FixedUpdate() {
|
|
if (!_initialized) return;
|
|
|
|
var input = CalculateInputs();
|
|
var output = _network.FeedForward(input);
|
|
|
|
_rigidbody.velocity = 2.5f * transform.up;
|
|
_rigidbody.angularVelocity = 500.0f * output[0];
|
|
|
|
_network.Fitness += 1.0f - Mathf.Abs(input[0]);
|
|
}
|
|
|
|
private float[] CalculateInputs() {
|
|
var inputs = new float[1];
|
|
|
|
var angle = transform.eulerAngles.z % 360.0f;
|
|
if (angle < 0.0f) angle += 360.0f;
|
|
|
|
var delta = (_target.position - transform.position).normalized;
|
|
var rad = Mathf.Atan2(delta.y, delta.x) * Mathf.Rad2Deg;
|
|
|
|
rad = rad % 360.0f;
|
|
if (rad < 0.0f) rad = 360.0f + rad;
|
|
|
|
rad = 90.0f - rad;
|
|
if (rad < 0.0f) rad += 360.0f;
|
|
|
|
rad = 360.0f - rad - angle;
|
|
|
|
if (rad < 0.0f) rad = 360.0f + rad;
|
|
if (rad >= 180.0f) rad = -(360.0f - rad);
|
|
rad *= Mathf.Deg2Rad;
|
|
|
|
inputs[0] = rad / Mathf.PI;
|
|
|
|
return inputs;
|
|
}
|
|
|
|
} |