This is my code for making a node move 'forwards' in the direction it's facing. If you're bored of having to draw a load of triangles and SOH/CAH/TOA every time, here is the maths you want:
Code: Select all
vector3df pos = node->getPosition();
vector3df rot = node->getRotation();
if(movingforwards)
{
f32 roty_rad = rot.Y * PI / 180; // convert to radians
pos.Z += PLAYER_SPEED * cos(roty_rad);
pos.X += PLAYER_SPEED * sin(roty_rad);
}
if(movingbackwards)
{
f32 roty_rad = rot.Y * PI / 180; // convert to radians
pos.Z -= PLAYER_SPEED * cos(roty_rad);
pos.X -= PLAYER_SPEED * sin(roty_rad);
}
if(strafingleft)
{
f32 roty_rad = rot.Y;
roty_rad -= 90;
roty_rad *= PI / 180;
pos.Z += PLAYER_SPEED * cos(roty_rad);
pos.X += PLAYER_SPEED * sin(roty_rad);
}
if(strafingright)
{
f32 roty_rad = rot.Y;
roty_rad += 90;
roty_rad *= PI / 180;
pos.Z += PLAYER_SPEED * cos(roty_rad);
pos.X += PLAYER_SPEED * sin(roty_rad);
}
if(turningleft)
{
rot.Y -= PLAYER_ROTATE;
}
if(turningright)
{
rot.Y += PLAYER_ROTATE;
}
node->setPosition(pos);
node->setRotation(rot);
PLAYER_ROTATE and PLAYER_SPEED are just scale factors to adjust how fast the player can move and turn.
The sin/cos functions in math.h take the angle argument in radians, so we need to convert the y rotation value.
I've implemented strafing by simply adding or subtracting 90' to the angle and using the same code as moving forwards.