How to Sync GameObject Creation to The Beat of a Song?
I am currently working on a simple VR rhythm game, and my main goal right now is to create a GameObject in time with the rhythm of a song currently playing. The game already knows the bpm of the song. I am not worrying about spawning the object right on the beat, but in time with the rhythm.
This is the current script I have running. The script gets close but still creates objects at a slightly quicker interval than the song's bpm. Any Advice?
public GameObject note;
public GameObject[] laneStart;
public float bpm;
private float lastTime, deltaTime, timer;
void Start () {
lastTime = 0f;
deltaTime = 0f;
timer = 0f;
}
// Update is called once per frame
void Update () {
//Chooses a random lane to create the note in
int rand = Random.Range (0, 4);
deltaTime = GetComponent<AudioSource> ().time - lastTime;
timer += deltaTime;
if (timer >= (60f/bpm)) {
//Create the note
((GameObject)Instantiate (note, laneStart [rand].transform.position, laneStart [rand].transform.rotation)).GetComponent<Transform> ().parent = GetComponent<Transform> ();
timer = 0;
}
lastTime = GetComponent<AudioSource> ().time;
}
Answer by Inv · Jun 17, 2016 at 01:46 PM
Sorry for coming back to this topic so late for those who were looking for a similar answer!
The reason I was getting a slightly quicker interval than normal was because of line 24:
timer = 0;
Because I was working with timing that needed very high accuracy, the extra ~.01 seconds that was on timer when it hit that line of code brought it out of sync by a small amount. After 30 seconds of many slightly out of sync beats, I would find the notes coming in ~.25 seconds late (not good for a rhythm game). To account for the delay, I changes line 24 to something like this:
timer -= (60f/bpm);
This way when we go .01 seconds over, the timer would start at .01, accounting for the delay. Hope this helped anyone with the same problem!
Answer by Dashz · Mar 10, 2018 at 01:50 PM
I know you were asking, but this helped me a lot, do you know how it would be possible to make the action at each 2nd note, you know most of the songs have 2 bass and 2 claps, bass - clap - bass - clap.
How could you make so that the action happens each clap?
EDIT: After many tries (because I didn't understand the logarithm you used as I'm not very talented in logic), just by starting the "timer" at 60f/bpm would solve this, just a "quarter of compass", since we are adding a beat as a starting point. Note that I used 120f/bpm and a delay of 60f because I wanted a slower action, so the stuff happens every 2 beats.