Rewind
Coding

Advanced Movement

Trigonometry, biatch!

In Basic Movement we covered movement where forces acted in two directions. But what if we needed to make a top down racer like supersprint or a game like Thrust where the object can turn and thrust around 360 degrees? For this we will need to use some trigonometry - all that scary cos/sin stuff.

Think of Thrust where you have a ship which can be pointed in any direction and any power applied will force it to accelerate in the direction it is facing.

We will use most of the variables we used in the first tutorial but we will need one more for the moment, direction, which will hold a value between 0 an 359 to represent the direction we are facing.

We need to translate the up/down,leeft/right movements into 360 degree control, ie left and right keys will turn the ship and up will apply force in the direction the ship is pointing.

To implement the turning all we need to do is replace the operations performed when left and right are pressed. Instead of altering X, Xvel or Xacc we want to amend the direction variable.

Assuming direction 0 degrees is pointing upwards and the angle direction increases in the clockwise direction...

If left is pressed we -5 (degrees) to direction
If right is pressed we +5 from direction

Now we need to implement the effect of thrusting in the current direction. To do this we will introduce a new acceleration variable, thrust, for acceleration in the current direction. Using this thrust acceleration and the current direction we will calculate how fast it's accelerating in the X and Y directions thus giving us xaccel and yaccel (which will in turn give us xvel and yvel)

Now we get to the point were we try and dig up those evil memories of high school trigonometry! Remember the right angle triangle? Well here it is with all the names of the sides...

The origin is where the direction angle is, ie your current x,y position

The hyp is the angled line opposite the right angle. This is effectively your thrust value and the other two sides make up your yacc and xacc values. You will notice that if you moved at this angle by the value of 'thrust', your new coords would be x+xacc and y+yacc

To calculate yaccel an xaccel we need to use some trig. There are two equations that you need to remember:

Cos(angle) x hyp = adj
Sin(angle) x hyp = opp

So... Cos(direction) x thrust will give you yacc and sin(direction) x thrust gives you xacc

Xacc=thrust x sin(direction)
Yacc=thrust x cos(direction)

You will then add these acceleration variables to xvel and yvel and using these, update x & y.

Not so hard, was it?

All content is (C) 2005 Rewind unless otherwise stated