0 votes

Perhaps what I am asking is more of a logic issue than specifically a Godot one, but I am not sure whether Godot has some useful built in functions to help this.

Essentially what I need to do is shuffle the music for a game and prevent tracks from repeating before other tracks have played. I can figure out how to randomize the music choices but I don't know the best way to make sure the same track isn't played back-to-back. I also need to be sure that whatever solution I use to do this won't completely prevent the track from playing again, say a few tracks later.

Thanks in advance. Love how helpful and welcoming this community is to noobs like myself!

asked Mar 31 in Engine by fader (46 points)

1 Answer

+3 votes
Best answer

If you really just want to ensure that a track doesn't play twice in a row (or similar), you could just remember the last track (or two, or ??) and use that to assist in the next track's selection. So, randomly select a track. If that track is the one you just played, select again. In pseudo-code, something like:

var newTrack = randomlySelectTrack()
while newTrack == prevTrack:
    newTrack = randomlySelectTrack()
prevTrack = newTrack
return newTrack

You could remember a number of previously selected tracks depending on your needs. Really though, you just want to "select again" if the track was recently played. If you need to skip some number of times before a replay becomes possible, you could manage the previously played tracks in another array. But, again, if the newly selected track "has been played recenlty" (is in the previously played array), just select again until a valid track is found.

Alternatively, if you want to play every track before one repeats, I'd suggest that as you play a track, you physically remove it from the array of available tracks. That way, you only have "non-played" tracks to choose from on each selection. Once the last track is selected and removed, you'd then restore the original array and start again.

answered Mar 31 by jgodfrey (5,742 points)
edited Mar 31 by jgodfrey

This solution works perfectly, thanks. So simple, too, I must have been overthinking!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.