forked from Gkxd/Rhythmify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_AbstractRhythmObject.cs
More file actions
68 lines (54 loc) · 2.14 KB
/
Copy path_AbstractRhythmObject.cs
File metadata and controls
68 lines (54 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* @Author: Gkxd
*
* Contains basic framework that syncs objects to the beat
*
* */
using UnityEngine;
using System.Collections;
namespace Rhythmify {
public abstract class _AbstractRhythmObject : MonoBehaviour {
protected int BPM;
protected float samplesPerBeat;
protected float secondsPerBeat;
private AudioSource audioSource;
private AudioClip audioClip;
private int lastBeatUpdate = -1;
private int beatCount = 0;
public void Start() {
GameObject[] bgmContainers = GameObject.FindGameObjectsWithTag("Rhythmify_Music");
if (bgmContainers.Length > 1) {
Debug.LogError("This scene contains more than 1 background music.");
Debug.Break();
}
else if (bgmContainers.Length < 1) {
Debug.LogError("This scene must contain 1 GameObject tagged with \"Rhythmify_Music\".");
Debug.Break();
}
GameObject bgmContainer = GameObject.FindGameObjectWithTag("Rhythmify_Music");
audioSource = bgmContainer.GetComponent<AudioSource>();
audioClip = audioSource.clip;
BPM = bgmContainer.GetComponent<MusicWrapper>().BPM;
secondsPerBeat = 60.0f / BPM;
samplesPerBeat = secondsPerBeat * audioClip.frequency;
init();
}
public void Update() {
int beat = (int)(audioSource.timeSamples / samplesPerBeat);
if (beat != lastBeatUpdate) {
lastBeatUpdate = beat;
rhythmUpdate(beatCount++);
}
asyncUpdate();
}
protected bool onBeat(float deltaSeconds) {
float beatOffset = audioSource.timeSamples % samplesPerBeat;
float deltaSamples = deltaSeconds * audioClip.frequency;
return beatOffset < deltaSamples || samplesPerBeat - beatOffset < deltaSamples;
}
protected virtual void init() {
}
protected virtual void asyncUpdate() {
}
protected abstract void rhythmUpdate(int beat);
}
}