# 3D: First Person Movement

I've searched and searched for a solution today but haven't found one.

I have a Camera with Vector3 and also the camera has an angle.

If I use this:

hero.position.x += speedX;
hero.position.z += speedZ;


works great but as soon as I rotate the camera the "hero" still goes in the same direction. So if I press button W I want the hero to go the way the camera is looking.

I've also tried:

hero.position.x += Math.sin(hero.rotation*3.1415/180) * speedX;
hero.position.z += Math.cos(hero.rotation*3.1415/180) * speedZ;


But it wont work and I just can walk in a line.

So how do I move in 3D space in first person mode?

You need to find a vector that points in the direction the camera is looking and then multiply this vector by your forward movement speed.

So you need to create a Matrix that rotates a Vector x-degrees around the Y-axis. Now I don't know what framework you're using (it just says java in your tags) so I'll just give some sample code that you need to adapt:

float degrees = 90; //degrees your camera is rotated along the y-axis
Vector3 forward = new Vector(0,0,-1);


Moving your player can now be done using the above forward vector

player.X += speed * forward.Z;
player.Y += speed * forward.Y;
player.Z += speed * forward.Z


Now if you're making a FPS you might also want to add strafing, this can be done easily by taking the forward vector, and rotating it another 90 degrees, you then have the 'left' vector which you can add as above the player's position where speed is 1 when 'strafe-left' is pressed, -1 when 'strafe-right' is pressed and 0 when nothing is pressed

You can also get the left vector by using the cross vector of the forward vector and the up vector (0,1,0).

In my example x is left-right, y is up-down, z+ screen to you z- screen to 'inside' of screen.

Edit: important note, you should always calculate a new forward vector every frame, don't re-use it and apply new rotations to the forward vector since small errors, that eventually become large errors, will creep in.

• or if he have access to the direction as a Quaternion orientation;, just: forward = orientation * new Vector3(0, 0, -1); backward = -forward; left = orientation * new Vector3(-1, 0, 0); right = -left; :D – Gustavo Maciel May 4 '12 at 18:18

Do you have a vector to the "look" point?

If so, just increase the player position by a vector speed*(eyePositionToLookPoint)

eyePositionToLookPoint = look - eye ;
eyePositionToLookPoint.normalize() ;
playerPos += speed*eyePositionToLookPoint ;


Be sure to normalize()!