Constantly updating average rpm

Hi.

I’m making a cycling game and with some help from a couple of users I’ve managed to clean up my code a little and found out how to calculate the average. The only problem is, it only calculates the average from the start of the game until the end. I need an average that updates as often as possible whilst staying reasonably accurate.

If you’ve ever used a cycling computer with a cadence sensor, you’ll know what I mean (hopefully)!

I managed to get a setup working in GameMaker that used 12 alarms. I delayed the start of each alarm by 0.5 seconds, and then there was a wait time of 6 seconds, so the result was updated every half of a second. Then I multiplied the results by 10 to get the rpm.

In Unity I can’t figure it out without using incredibly messy code which tells me that I’m doing something wrong.

Any help?
Thanks a lot.

Ps. On cycling computers with cadence sensors, you get very accurate RPM readings. 85, 86, 87, etc. Using my method (taking the input over 6 seconds and multiplying it by 10) this isn’t possible as you’ll always get a result ending in 0.

I’m really, really confused…

Choose an arbitrary frame rate, let’s say 60 frames per second.

Now choose how many seconds you want to have in your time-weighted average, let’s say 10 seconds.

Make an array that contains that many floats, in this case 600 floats.

Now every frame move a counter along and store the current value at that indexed position. When you reach 600, wrap back around to 0.

To keep it simple, every frame just add up all the numbers and divide by 600. That’s your running average.

If you wanna be more efficient about it, you can keep a separate “running total”, and whenever you go stick a number into a slot, first read the number that was there BEFORE you store it, and subtract that amount from your running total. Now add your new amount to the running total and store it into the array. Obviously divide this running total by the 600 frame count before you display it. Don’t store the divided value obviously.

This way is a lot more efficient than brute-forcing an array average every frame, but you have to ensure your array and your running total are “in sync” at the start of your simulation, which they would be if everything was zero to start.