Object speed and UpdateRate (FPS).

Monkey Forums/Monkey Programming/Object speed and UpdateRate (FPS).

Alex(Posted 2015) [#1]
Hello everyone!
Hope you're all good ;)

I have no doubt many of you faced this problem.

Lets say we have a bullet that flies towards its target. Once it reaches that target you get a point.
And let's say the goal is time sensitive.

The problem is. I need to make the bullet fly with the same speed no matter the FPS.
Because if we simply add a pixel each time Update method calls, the program will add a pixel faster with 60 FPS than with 40 FPS.

I came up with this:
Method Update:Void()
    spd = (Millisecs() - dist) / 10
    x += spd
    dist = Millisecs()
End Method


But in this example, the slower the FPS the smaller the spd! Why?
However, my brain tells me, the more time to update the screen, the bigger the spd.

Either I'm stupid today, or I know nothing about how Update works (or how to move things) at all. If so, please explain me this and forgive me my ignorance.

BTW: tried OnRender. The result is the same.

Thank you!


MikeHart(Posted 2015) [#2]
Exactly. With slower FPS, the spd value becomes bigger as Millisecs becomes bigger. Why you set the dist via Millisecs is beyond me. Why to use dist anyway? Just add your calculated speed factor to your X position.


Alex(Posted 2015) [#3]
Let's try some pseudo code.

From the last cycle, dist = Millisecs, say = 100 ms

One cycle later... (+60 ms)

160th ms: Update start. 
   spd = (160 - 100) / 10 = 60 / 10 = 6px
   x += 6px
   dist = 160
End Update


Again +60 ms...

220th ms: Update start. 
   spd = (220 - 160) / 10 = 60 / 10 = 6 px
   x += 6px
   dist = 220
End Update


Now lets say the game slows down.
The update time becomes bigger.
So program needs 80ms instead of 60 to update.

80ms later

300th ms: Update start. 
   spd = (300 - 220) / 10 = 80 / 10 = 8px
   x += 8px
   dist = 300
End Update


The bullet now should move 8 pixels. Right?

Now try it, it will slow down =(
When I print spd, and FPS drops, the bullet slows down too. Why?


Alex(Posted 2015) [#4]
Solved =)

The processor ate some extra ms from start of update to its end.
So when I reseted the DIST to Millisecs, it was a bit bigger than at the start of Update.

Here's the right code.
Method Update:Void()
    spd = (Millisecs() - dist)
    dist += spd
    x += spd / 10
End Method


2 MikeHart:
Thanks! You pushed me to the right answer!
I know, it seems stupid to use dist variable. But I need it only because I divide the time by 10.
If I want to add the whole time to my distance, I do something like this (note: this example is without "/ 10"):
Method Update:Void()
    spd = (Millisecs() - x)
    x += spd
End Method



UPD:
Fixed the firs code box.


MikeHart(Posted 2015) [#5]
It will only work if dist or X will be lower than Millisecs. If they are bigger, then you bullet will move backwards.
I would scrape the distance and use only a speedfactor that is influenced by Millisecs.