2D Game Physics - Part II - Acceleration

- benjamin805 benjamin805


Acceleration

In some games accelerating objects is needed to show a speed increase. In this example we see how adding a constant
acceleration value to the speed of a missile increases the distance traveled each time the graphic screen is updated.


'Window Setup
nomainwin
WindowWidth=400
WindowHeight=400
open "Missle Launch" for graphics_nsb as #main
#main,"trapclose [exit]"
 
'launch angle (0-360)
angle=90
'convert angle to radians
AngleInRadians=angle/57.29577951
 
'set missile starting values
movingObject.speed=2
movingObject.acceleration=1 'constant acceleration
 
'starting position
movingObject.x=200
movingObject.y=370
 
'set direction of movement by getting
'the cos and sin of the angle in radians
scale.x=cos(AngleInRadians)
scale.y=sin(AngleInRadians)
 
#main,"down;color red;size 5"
 
timer 100,[loop]
 
wait
 
[loop]
'add our constant acceleration to the speed
movingObject.speed=movingObject.speed+movingObject.acceleration
 
#main,"up;goto 0 12;down;\Speed: ";movingObject.speed
'increase the object velocity by multiplying our new speed by our
'scale value
movingObject.velocity.x=(movingObject.speed*scale.x)
movingObject.velocity.y=(movingObject.speed*scale.y)
'add our new velocity value to our current movingObject x and
'y values
movingObject.x=movingObject.x+movingObject.velocity.x
movingObject.y=movingObject.y-movingObject.velocity.y
 
#main,"set ";movingObject.x;" ";movingObject.y
 
if movingObject.y<0 then
    timer 0
    wait
    end if
wait
 
[exit]
close #main
end