3
\$\begingroup\$

I want to make a game object move in directions relative to the direction it is facing. That is, if the user presses the "W" key the object goes "forward"; if they press "D" the object goes to its left. etc

The letters represent the key board the user is pressing w so the object moves up

Here the object its rotated so it moves on that direction

So far I am having trouble, because I can't make it move in the correct direction when its rotated.

I just want some pseudo code to point me in the right direction, thank you.

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

One way to do it is to keep track of the Front and Up normalized vectors and transform the front vector whenever your character turns, and calculate the Right vector using cross product ( I am assuming Up vector won't rotate). Or you can keep track of the three vectors and rotate them. Once you rotate them you update the position by adding the offset in the needed direction.

In order to move the position in the intended direction you only need to add the front or right vector to the position given that

front = Rotate(front, degree); 
vec3 right = Cross(front, up);
// if player input D
position += right;
// if player input W
position += front;

You only need to negate the front/right vector if the player presses A or S

\$\endgroup\$
0
\$\begingroup\$

I think some trigonometry classes would help you.

Meaning of variables position.x is the x coordinate, and position.z is the y (if 2D game) or z (3D game) coordinate. Yaw is the rotation (in radians I think). So when user presses A do yaw--; and when user presses S do yaw++;. Distance is how far to move (sort of like speed).

NOTE: This is written in Java. Converting to c/c++/c# should be no problem. Also, remember to replace position.x and position.z with the variables your using for x and y.

public void walkForward(float distance)
{
    position.x -= distance * (float)Math.sin(Math.toRadians(yaw));
    position.z += distance * (float)Math.cos(Math.toRadians(yaw));
} 
//moves the camera backward relative to its current rotation (yaw)
public void walkBackwards(float distance)
{
    position.x += distance * (float)Math.sin(Math.toRadians(yaw));
    position.z -= distance * (float)Math.cos(Math.toRadians(yaw));
}
//strafes the camera left relitive to its current rotation (yaw)
public void strafeLeft(float distance)
{
    position.x -= distance * (float)Math.sin(Math.toRadians(yaw-90));
    position.z += distance * (float)Math.cos(Math.toRadians(yaw-90));
} 
//strafes the camera right relitive to its current rotation (yaw)
public void strafeRight(float distance)
{
    position.x -= distance * (float)Math.sin(Math.toRadians(yaw+90));
    position.z += distance * (float)Math.cos(Math.toRadians(yaw+90));
}

My Source

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .