Archived
Private
Public Access
1
0
This repository has been archived on 2026-02-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
2023-07-31 21:20:56 +02:00

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;
}
}