Question

I need a way(in java) to calculate which direction my camera will move forward on the x and z axes based on the direction my camera is facing(yaw), and for y(the vertical axis), the pitch. I'm making my own game engine and my own camera.

With all values defaulting at zero, moving the camera correctly directs all movement along the positive z axis. However, when I pan the camera to the left or right(thereby changing the yaw), the camera still only moves along the z axis... So how do I calculate the change in direction to the x, y, and z axes?

The value range on the yaw is 0(south), 45(southwest), 90(west), 135(northwest), 180(north), 225(northeast), 270(east), 315(southeast), and back to 360(south, same as 0).

What I'm looking for with the compass directions(where a '+' or '-' indicates a change in value along that axis):

South = x, y, z+
SouthWest = x+, y, z+
West = x+, y, z
NorthWest = x+, y, z-
North = x, y, z-
NorthEast = x-, y, z-
East = x-, y, z
SouthEast = x-, y, z+

The value range on the pitch is 0.0(middle), 100.0(up all the way), and -100.0(down all the way).

If I need to post some code, I can, but it might get complicated. I hope I'm making some kind of sense so that someone can help me!

Was it helpful?

Solution

Suppose you want to move the camera in direction y with distance k. For the sake of simplicity, i will convert your directions to angles, where 0.0 represents right, Pi/2 represents up, Pi represents left, 3*Pi/2 represents down and so.

EDIT: As you say y of camera will be affected only by the pitch. X and z, instead will be affected by both the yaw and the pitch.

You can calculate the new x, y and z by the following:

float y = // Yaw angle
float p = // Pitch angle
float k = // Move distance

float xzLength = cos(p) * k;
float dx = xzLength * cos(y);
float dz = xzLength * sin(y);
float dy = k * sin(p);

// Update your camera:
camera.x += dx;
camera.y += dy;
camera.z += dz;

Obviously, yaw and pitch do not change, so you don't need to update them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top