Counters and Modulo - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki
We can use p5's frameCount variable to determine which frame we are on to perform time based events.
A sound machine
A sound machine requires sounds to played at specific times.
For example we may want a drum beat to be played 3 times per second. If the frame rate is 30 fps then we would need to play the drum sound every 10 frames.
How do we know if 10 frames have passed?
There are two ways we could do it:
- Counter
- Modulo
Counter
The counter approach requires a counter which is updated every frame, and reset every 10 frames. As an example:
var counter = 0;
function draw() {
counter++;
if (counter == 10) {
counter = 0;
// play sound
}
}
Modulo
The modulo operation doesn't require us to keep a separate count, we can use the global frameCount variable to determine if the required number of frames have passed. You can see an example of the frameCount variable running in the reference.
The modulo operator is %. It operates similar to a division except that it gives you the remainder, very handy for what we want to do. Note that the frameCount will continue increasing forever until infinity, but we just want to know chunks of 10 frame counts. We can achieve this by dividing the frameCount by 10 and the remainder will be a number between 0 and 9. It effectively becomes a counter that loops between 0 and 9.
This is how you can use it:
var counter = frameCount % 10;
if (counter == 0) {
// play sound
}