Speed
In real-world physics, motion happens at a rate based on time. The rate of motion is more commonly (and less technically) known as speed. Speed is typically expressed in this mathematical equation :
speed = distance / time
This is fine if you want to calculate speed of something, but in 2D physics speed is rarely measured rather than is set. For 2D game physics, the equation looks like this :
position = position + distance (in ppl)
This is used because as game programmers, we are making things move rather than idly sitting by measuring their speed. Therefore speed is created by moving an objects position a distance in pixels per loopin. Since the object is moved in intervals of loopins, a measurement of time, the basics of the common equation remain — even if beaten with a large stick.
This equation is valid for setting the speed of a game object either vertically or horizontally. Horizontally, the equation is applied to x# and vertically, it is applied to y#.
Here's a code example that makes a dot move at 2 ppl across the screen :
x# = 0
y# = 300
xSpeed# = 2 ; remember, 2 ppl
SetFPS 60
Do
; add the speed to the position
; position = position + speed
x# = x# + xSpeed#
; draw frame
Cls 0
Dot x#, y#
Sync
Loop
If you increase the distance moved per loopin, you increase the speed. In the case of the code above, only horizontal speed is applied.
Also notice that the speed is added to the position. This is very important. A positive speed moves the dot right. A negative speed moves the dot left. This is possible because when you add a negative number to anything, subtraction actually occurs.
A Word About Speed and Teleportation
In the real word, objects have to travel all the space between point A and point B. For game objects this is not always true. If a game object's speed is greater than 1, then it is said to be teleporting. This is not normally an issue, however, if a game object is traveling at a greater speed than the object is long, then it could possibly teleport right through other objects without touching them.
Naturally, if the teleporting game object doesn't touch anything, there can be no collision detection (in the traditional sense.)
Teleportation will be dealt with in it's own chapter. In the meantime, the below code will illustrate the concept.
x# = 0
y# = 300
xSpeed# = 20 ; 20 ppl
SetFPS 60
Do
; add the speed to the position
; position = position + speed
x# = x# + xSpeed#
Dot x#, y#
Sync
Loop
Cls has been removed and the xSpeed# increased to 20. Removing Cls will cause the screen not to be cleared, and therefore show you the gaps in between each teleport. With standard collision detection, the dot will not have collided with anything in the gaps you see.