Inertial movement using vectors (asteroids by ESC_12th Oct 2003 23:06
|
---|
Summary drifting inertial movement with friction Description This is just a quick snippet I put together for people who want to create drifting and momentum in their games using vectors. Code ` This code was downloaded from The Game Creators ` It is reproduced here with full permission ` http://www.thegamecreators.com remstart How to use vectors-making a small asteroids-style movement demo By ESC The idea behind this is quite simple A vector is a unit that can store both magnitude and direction (5 feet north, for example) In this snippet, there are two vectors, the main vector of the ship, and another 'component' vector which will be added to the main vector. How does vector addition work? |.................... |.................... |......cb............ |.....c.b............ |....c..b............ |...c...b............ |..c...aa............ |.c..aa.............. |c.aa................ |aa.................. if vector a was added to vector b, logically they would add to be vector c. All you need to do is first add the x components of the two vectors, and then add the y components, and voila, you have your new vector! remend `initilization set display mode 1024,768,32 set window off backdrop on color backdrop 0 sync on:sync rate 60:hide mouse `load in ship sprite image load image "ship.bmp",1 `x & y coords and angle of the ship x#=300 y#=300 angle#=0 `component vector magnitude(acceleration of ship) accel#=0.1 `friction value-must be >1 `the closer it is to 1, the less friction there is `This is because the main vectors of the ship are devided by this value friction#=1.005 `turn rate of ship turnrate#=2 `set up a vector type type vector x as float y as float endtype `set up the ship's main vector shipv as vector shipv.x=0 shipv.y=0 `setup component vector for vector addition comv as vector comv.x=0 comv.y=0 `make the sprite sprite 1,x#,y#,1 offset sprite 1,49,37 do `rotate the ship if rightkey()=1 then angle#=angle#-turnrate# if leftkey()=1 then angle#=angle#+turnrate# angle#=wrapvalue(angle#) rotate sprite 1,wrapvalue(-1*(angle#+180)) `calculate the component vector (added to the main vector if upkey is pressed) comv.x=sin(angle#)*accel# comv.y=cos(angle#)*accel# `ship movement if upkey()=1 `add the vectors together to produce a final vector shipv.x=shipv.x+comv.x shipv.y=shipv.y+comv.y endif `calculate friction shipv.x=shipv.x/friction# shipv.y=shipv.y/friction# `check to make sure ship isn't offscreen (that way you can't lose the ship if x#<0 then x#=screen width() if x#>screen width() then x#=0 if y#<0 then y#=screen height() if y#>screen height() then y#=0 `reposition the ship x#=x#+shipv.x y#=y#+shipv.y sprite 1,x#,y#,1 set cursor 0,0:print screen fps() sync loop |