void PlayerInputted() { // Start the song if it isn't started yet. if (!songStarted) { songStarted = true; StartSong(); statusText.text = ""; return; } // Play the beat sound. beatAudioSource.Play(); if (notesOnScreen.Count > 0) { // Get the front note. MusicNote frontNote = notesOnScreen.Peek(); // Distance from the note to the finish line. float offset = Mathf.Abs(frontNote.gameObject.transform.position.x - finishLineX); // Music note hit. if (offset <= tolerationOffset) { // Change color to green to indicate a "HIT". frontNote.ChangeColor(true); statusText.text = "HIT!"; // Remove the reference. (Now the next note moves to the front of the queue.) notesOnScreen.Dequeue(); } } }
void Update() { // Check key press. if (Input.GetKeyDown(KeyCode.Space)) { PlayerInputted(); } if (!songStarted) { return; } // Calculate songposition. (Time passed - time passed last frame). songposition = (float)(AudioSettings.dspTime - dsptimesong - songOffset); // Check if we need to instantiate a new note. (We obtain the current beat of the song by (songposition / secondsPerBeat).) // See the image for note spawning (note that the direction is reversed): // http://shinerightstudio.com/posts/music-syncing-in-rhythm-games/pic2.png float beatToShow = songposition / secondsPerBeat + BeatsShownOnScreen; // Check if there are still notes in the track, and check if the next note is within the bounds we intend to show on screen. if (indexOfNextNote < track.Length && track[indexOfNextNote] < beatToShow) { // Instantiate a new music note. (Search "Object Pooling" for more information if you wish to minimize the delay when instantiating game objects.) // We don't care about the position and rotation because we will set them later in MusicNote.Initialize(...). MusicNote musicNote = ((GameObject)Instantiate(musicNotePrefab, Vector2.zero, Quaternion.identity)).GetComponent <MusicNote>(); musicNote.Initialize(this, startLineX, finishLineX, removeLineX, posY, track[indexOfNextNote]); // The note is push into the queue for reference. notesOnScreen.Enqueue(musicNote); // Update the next index. indexOfNextNote++; } // Loop the queue to check if any of them reaches the finish line. if (notesOnScreen.Count > 0) { MusicNote currNote = notesOnScreen.Peek(); if (currNote.transform.position.x >= finishLineX + tolerationOffset) { // Change color to red to indicate a miss. currNote.ChangeColor(false); notesOnScreen.Dequeue(); statusText.text = "MISS!"; } } // Note that the music note is eventually removed by itself (the Update() function in MusicNote) when it reaches the removeLine. }