PDA

View Full Version : Trig for random character movement

Random89
03-28-2009, 10:14 AM
I am writing a game using OpenGL (with C++) and I trying to make a character turn and walk in the direction he is facing.

srand(time(NULL));
float dir = rand() % 72; //As I am using directions 5 apart there are 72 to make a full circle
dir = dir * 5;
float lecDist = 0.05;
float fulldir = fulldir + dir; // total direction turned, starts at 0 and each time character turns it is added on
if (fulldir > 360)
{
fulldir = fulldir - 360; // if it is over 360 it starts again at 0
}
Vlec = Vlec + (0.05 * sin(fulldir)); //Hlec and Vlec are defined somewhere else, each value then has its counterpart of the 0.05 moved
Hlec = Hlec + (0.05 * cos(fulldir));
glTranslatef(Hlec, Vlec, 0); //Moves the object Hlec across and Vlec up
glRotatef(dir, 0, 0, 1); //Rotates object round point 0,0,1 (x,y,z) by dir degrees
drawLec(0, 0); //Draws the object (calls lec)

The main problem is with the trig, I am trying to move the object 0.05 units in the direction he is facing so I am using the formula:
opp = sin(x) * hyp
adj = cos(x) * hyp

Where hyp is the hypotenuse (in this case 0.05), opp is the Y axis (Vlec) and adj is the X axis (Hlec). It is is basically saying instead of going across the hypotenuse I can go across the opposite angle and the adjacent angle (see sohcahtoa on google).

Anyone know what could be wrong with my maths?

Stuart McDonald
03-28-2009, 11:20 AM
sin and cos take radians not degrees.

enunes
03-28-2009, 10:36 PM
Hi,

also

float fulldir = fulldir + dir; // total direction turned, starts at 0 and each time character turns it is added on
if (fulldir > 360)
{
fulldir = fulldir - 360; // if it is over 360 it starts again at 0
}

can be translated into

fulldir = (fulldir+dir)%360;

Random89
03-29-2009, 04:34 AM
Thanks, suddenly feeling very stupid now...