Add BeatPulseController for music synchronization and event handling

This commit is contained in:
2025-12-13 00:42:18 +01:00
parent eb1a1b224a
commit cd28adc8e9
9 changed files with 209 additions and 1 deletions

View File

@@ -0,0 +1,66 @@
using System;
using UnityEngine;
using UnityEngine.Events;
namespace Infrastructure.Unity
{
public class BeatPulseController : MonoBehaviour
{
[Header("Music Settings")]
[Tooltip("Beats Per Minute of your track")]
[SerializeField] private float bpm = 90f;
[Tooltip("Delay in seconds to sync the first beat with the music start")]
[SerializeField] private float startDelay = 0.0f;
[Header("Events")]
public UnityEvent OnBeat; // Fires every beat (1, 2, 3, 4)
public UnityEvent OnMeasure; // Fires every 4th beat (The Drop)
private float _beatInterval;
private float _timer;
private int _beatCount;
private bool _isRunning;
private void Start()
{
if (bpm > 0) _beatInterval = 60f / bpm;
}
public void BeginTracking()
{
_timer = -startDelay;
_beatCount = 0;
_isRunning = true;
}
public void StopTracking()
{
_isRunning = false;
}
private void Update()
{
if (!_isRunning) return;
_timer += Time.deltaTime;
if (_timer >= _beatInterval)
{
_timer -= _beatInterval;
Pulse();
}
}
private void Pulse()
{
_beatCount++;
OnBeat?.Invoke();
if (_beatCount % 4 == 0)
{
OnMeasure?.Invoke();
}
}
}
}