How does this snippet of code create a ray direction vector?

| | August 11, 2015

In the Minecraft source code, this code is used to create a direction vector for a ray from pitch and yaw:’

float f1 = MathHelper.cos(-rotationYaw * 0.01745329F - 3.141593F);
float f3 = MathHelper.sin(-rotationYaw * 0.01745329F - 3.141593F);
float f5 = -MathHelper.cos(-rotationPitch * 0.01745329F);
float f7 = MathHelper.sin(-rotationPitch * 0.01745329F);
return Vec3D.createVector(f3 * f5, f7, f1 * f5);

I was wondering how it worked, and what is the constant 0.01745329F?

2 Responses to “How does this snippet of code create a ray direction vector?”

  1. It works by using spherical coordinates. In particular see the section about converting to Cartesian coordinates. The Wikipedia article uses a slightly different convention for the definitions of the angles than your code, resulting in some sin / cos factors being swapped, but it’s the same idea.

  2. 0.01745329F is the conversion rate between degrees and radians. Degrees are easier to understand but most mathematical functions need radians so this is a common conversion to perform. The -pi part just rotates the value further.

    I’ll let someone else address the trigonometry part. :)

Leave a Reply