1
0
mirror of https://projects.caleb-brown.dev/UDRI-XRT/UDRIGEEKCup2024.git synced 2025-01-22 07:08:51 -05:00
UDRIGEEKCup2024/Assets/GolfControls/BallHitController.cs
2024-04-24 11:02:50 -04:00

96 lines
2.4 KiB
C#

using System.Collections;
using UnityAtoms.BaseAtoms;
using UnityEngine;
namespace MAVRIC.GEEKCup.GolfControls
{
public class BallHitController : MonoBehaviour
{
public VoidEvent ballHitEvent;
public BoolEvent incrementStrokeCount;
public Vector3Variable AngleVariable;
public FloatVariable PowerVariable;
public BoolVariable isMovingVariable;
public BoolVariable inHoleVariable;
public float baseForce;
private Rigidbody body;
public AudioSource hitSoundSource;
private float minVelocityMagnitude = 0.1f;
private void Start()
{
body = gameObject.GetComponent<Rigidbody>();
}
private void OnEnable()
{
ballHitEvent.Register(OnHit);
}
private void OnDisable()
{
ballHitEvent.Unregister(OnHit);
}
private void OnHit()
{
if(isMovingVariable.Value) return;
if (body.velocity.magnitude >= minVelocityMagnitude) return;
hitSoundSource.Play();
Vector3 hitVector = AngleVariable.Value.normalized * (PowerVariable.Value * baseForce);
body.AddForce(hitVector);
StartCoroutine(TrackState());
}
private IEnumerator TrackState()
{
float ballStopTime = 1.0f;
isMovingVariable.SetValue(true);
incrementStrokeCount.Raise(true);
while (!inHoleVariable.Value)
{
yield return null;
if(body.velocity.magnitude >= minVelocityMagnitude) continue;
float timer = 0.0f;
bool isStopped = true;
while (timer < ballStopTime)
{
yield return null;
if (inHoleVariable.Value) break;
timer += Time.deltaTime;
if (body.velocity.magnitude > minVelocityMagnitude)
{
isStopped = false;
break;
}
}
if (isStopped) break;
}
body.velocity = Vector3.zero;
body.angularVelocity = Vector3.zero;
isMovingVariable.SetValue(false);
incrementStrokeCount.Raise(false);
}
}
}