lucid-super-dream/Assets/Scripts/TargetLockOn.cs

75 lines
2.0 KiB
C#
Raw Permalink Normal View History

2021-01-05 18:13:29 +01:00
using System.Collections.Generic;
using UnityEngine;
public class TargetLockOn : MonoBehaviour
{
[SerializeField] private Camera cam;
[SerializeField] private RectTransform cursor;
[SerializeField] private int maxTargets;
[SerializeField] private float targetSize;
[SerializeField] private LayerMask collideWith;
[SerializeField] private TransformEvent OnTargetFound;
[SerializeField] private TransformListEvent OnTargetLock;
2021-01-06 16:10:11 +01:00
[SerializeField] private int shootOnBeat;
[SerializeField] private int noTargetLengthInBeats;
[SerializeField] private float beatOffset;
2021-01-05 18:13:29 +01:00
private List<Transform> _targets;
private bool _canTarget = true;
private RaycastHit[] _colliders = new RaycastHit[128];
2021-01-06 16:10:11 +01:00
private AudioBeatManager _audio;
2021-01-05 18:13:29 +01:00
private void Awake()
{
_targets = new List<Transform>(maxTargets);
2021-01-06 16:10:11 +01:00
_audio = FindObjectOfType<AudioBeatManager>();
2021-01-05 18:13:29 +01:00
}
2021-01-06 16:10:11 +01:00
public void OnBeat(int beat)
2021-01-05 18:13:29 +01:00
{
2021-01-06 16:10:11 +01:00
if ((beat + beatOffset) % shootOnBeat == 0)
2021-01-05 18:13:29 +01:00
{
OnTargetLock?.Invoke(_targets);
_targets.Clear();
_canTarget = false;
}
2021-01-06 16:10:11 +01:00
if ((beat + beatOffset + noTargetLengthInBeats) % shootOnBeat == 0)
_canTarget = true;
}
private void FixedUpdate()
{
if (!_canTarget) return;
2021-01-05 18:13:29 +01:00
var ray = cam.ScreenPointToRay(cursor.position + Vector3.forward);
var numHits = Physics.SphereCastNonAlloc(ray, targetSize, _colliders, 50, collideWith, QueryTriggerInteraction.Collide);
if (numHits < 0) return;
for (int i = 0; i < numHits; i++)
{
if (_targets.Contains(_colliders[i].transform)) continue;
2021-01-09 17:18:29 +01:00
if (_targets.Count < maxTargets)
{
_targets.Add(_colliders[i].transform);
OnTargetFound?.Invoke(_colliders[i].transform);
}
2021-01-05 18:13:29 +01:00
if (_targets.Count >= maxTargets)
break;
}
}
2021-01-06 16:10:11 +01:00
}