Pitch/Yaw to Directional Vector

This calculation can take a pitch and yaw value and convert it into a directional 3D vector.

theagentd simplification(recommended)


// pitch and yaw are in degrees
Vector3D getDirectionVector() {
   double pitchRadians = Math.toRadians(pitch);
   double yawRadians = Math.toRadians(yaw);

   double sinPitch = Math.sin(pitchRadians);
   double cosPitch = Math.cos(pitchRadians);
   double sinYaw = Math.sin(yawRadians);
   double cosYaw = Math.cos(yawRadians);

   return new Vector3D(-cosPitch * sinYaw, sinPitch, -cosPitch * cosYaw);
}

In this circumstance, pitch and yaw are easier to keep in degrees, personally. But for improved performance, by all means, translate this to go to radians(just put pitch or yaw instead of (pitch or yaw) * PI / 180)


// pitch and yaw are in degrees
Vector3D getDirectionVector() {
   double pitchRadians = Math.toRadians(pitch);
   double yawRadians = Math.toRadians(yaw);

   double sinPitch = Math.sin(pitchRadians);
   double cosPitch = Math.cos(pitchRadians);
   double sinYaw = Math.sin(yawRadians);
   double cosYaw = Math.cos(yawRadians);

   return new Vector3D(-cosPitch * sinYaw, sinPitch, -cosPitch * cosYaw);
}

1 less cos() call, a lot of fewer multiplies and divides…

My recommendation is to not use euler angles (at least at runtime) to represent orientations. Likewise for degrees (use radians).

It’s practical for a first person camera?

I personally won’t, but yeah that would be an example of a reasonable usage. Another would be flight simulation.

Follow up: remember when you’re talking about cameras, then getting any of: forward, right & up vectors from the orientation is the same as converting it to a matrix which you’ll be most likely doing anyway. Of course this is true for any orientation that is going to get converted to matrix form.

I’ll modify the code to what theagentd posted. :slight_smile: I’m not much in the habit of simplifying code/equations if you saw my previous codes.

So…err…what exactly do you use this Vector for? :persecutioncomplex:

Think of a minecraft game.

You have a first person camera with yaw and pitch.

Then you want to get the block you click on. You create yourself this vector from your camera’s yaw and pitch, and then raycast the vector from the mid of your camera’s / eye’s position forward, until it hits a block (or doesn’t), and then you can mine it…

Oh! Right I knew that…

slaps himself silly a few times

Always glad to be able to help ;D