85 lines
1.9 KiB
C#
85 lines
1.9 KiB
C#
using UnityEngine;
|
|
|
|
namespace UltimateWater.Samples
|
|
{
|
|
public class SardineBoid : MonoBehaviour
|
|
{
|
|
[SerializeField]
|
|
private float _Speed = 1.5f;
|
|
|
|
[SerializeField]
|
|
private float _TurnSpeed = 1f;
|
|
|
|
[SerializeField]
|
|
private float _FollowTime = 1f;
|
|
|
|
[SerializeField]
|
|
private GameObject[] _Eyes;
|
|
|
|
public Transform Destination;
|
|
|
|
private Rigidbody _Rigidbody;
|
|
|
|
private Transform _Target;
|
|
|
|
private float _Cooldown;
|
|
|
|
private void Awake()
|
|
{
|
|
_Rigidbody = GetComponent<Rigidbody>();
|
|
Animator component = GetComponent<Animator>();
|
|
component.SetFloat("Forward", _Speed);
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (_Cooldown > 0f)
|
|
{
|
|
_Cooldown -= Time.deltaTime;
|
|
}
|
|
else
|
|
{
|
|
FindTarget();
|
|
}
|
|
if (base.transform.position.y > 0f)
|
|
{
|
|
_Rigidbody.AddForce(Vector3.down * (base.transform.position.y + 1f) * (base.transform.position.y + 1f) * 20f);
|
|
}
|
|
Rotate();
|
|
_Rigidbody.velocity = base.transform.forward * _Speed;
|
|
}
|
|
|
|
private void FindTarget()
|
|
{
|
|
GameObject[] eyes = _Eyes;
|
|
foreach (GameObject gameObject in eyes)
|
|
{
|
|
RaycastHit hitInfo;
|
|
if (Physics.Raycast(gameObject.transform.position, gameObject.transform.up, out hitInfo, 100f) && !(hitInfo.collider.attachedRigidbody == null))
|
|
{
|
|
GameObject gameObject2 = hitInfo.collider.attachedRigidbody.gameObject;
|
|
SardineBoid component = gameObject2.GetComponent<SardineBoid>();
|
|
if (component != null)
|
|
{
|
|
_Target = hitInfo.transform;
|
|
_Cooldown = _FollowTime / (hitInfo.distance + 1f);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
_Target = Destination;
|
|
}
|
|
|
|
private void Rotate()
|
|
{
|
|
if (!(_Target == null))
|
|
{
|
|
float maxDegreesDelta = _TurnSpeed * Time.deltaTime;
|
|
Vector3 normalized = (_Target.transform.position - base.transform.position).normalized;
|
|
Quaternion to = Quaternion.LookRotation(normalized);
|
|
base.transform.rotation = Quaternion.RotateTowards(base.transform.rotation, to, maxDegreesDelta);
|
|
}
|
|
}
|
|
}
|
|
}
|