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

80 lines
2.3 KiB
C#
Raw Normal View History

2021-01-05 18:13:29 +01:00
using System.Collections;
using DG.Tweening;
using UnityEngine;
2021-01-07 11:05:19 +01:00
using Utils;
2021-01-05 18:13:29 +01:00
public class MoveAfterDelay : MonoBehaviour
{
2021-01-06 16:10:11 +01:00
[SerializeField] private int beatsBeforeMove = 16;
[SerializeField] private float scaleAmount = 1.5f;
[SerializeField] private int numBeatsAfterScale = 4;
private static AudioBeatManager _audio;
private void Awake()
{
if (_audio == null)
_audio = FindObjectOfType<AudioBeatManager>();
}
2021-01-05 18:13:29 +01:00
private void OnEnable()
{
2021-01-06 16:10:11 +01:00
_audio.OnBeatEvent += AudioOnBeat;
}
private void OnDisable()
{
_audio.OnBeatEvent -= AudioOnBeat;
}
private void AudioOnBeat(int beat)
{
if (beat % beatsBeforeMove != 0) return;
2021-01-07 11:05:19 +01:00
var pos = transform.localPosition;
pos.z = 0;
var dir = pos.normalized;
pos = transform.localPosition;
DoAnim(pos, dir).Run();
}
private IEnumerator DoAnim(Vector3 pos, Vector3 dir)
{
var keepGoing = true;
var startTime = _audio.DspTime;
var targetDSPTime = _audio.TimeBetweenBeats * .25f;
while (keepGoing)
{
var currentDSPTime = _audio.DspTime - startTime;
var t = currentDSPTime / targetDSPTime;
transform.localScale = Vector3.Lerp(Vector3.one, Vector3.one * scaleAmount, 1 - Mathf.Pow(1 - t, 5));
transform.localPosition = Vector3.Lerp(pos, pos + dir * 4, t);
if (currentDSPTime >= targetDSPTime)
keepGoing = false;
yield return null;
}
startTime = _audio.DspTime;
keepGoing = true;
targetDSPTime = _audio.TimeBetweenBeats * .25f;
while (keepGoing)
{
var currentDSPTime = _audio.DspTime - startTime;
var t = currentDSPTime / targetDSPTime;
transform.localScale = Vector3.Lerp(Vector3.one* scaleAmount, Vector3.one, t*t*t*t*t);
transform.localPosition = Vector3.Lerp(pos + dir * 4, pos, t);
if (currentDSPTime >= targetDSPTime)
keepGoing = false;
yield return null;
}
yield return new WaitForSeconds(_audio.TimeBetweenBeats);
transform.DOMoveZ(-30, _audio.TimeBetweenBeats * 2).SetEase(Ease.OutQuint);
2021-01-05 18:13:29 +01:00
}
2021-01-06 16:10:11 +01:00
}