3
\$\begingroup\$

I have a simple question on usage of math.Atan2 function with Unity in a 3D environment.

I found this code on Unity's documentation for Math.Atan2. I changed it a bit to fit my needs.

Vector3 waypoint = Random.insideUnitSphere + new Vector3(Random.Range(minX+1.5f, maxX-1.5f),prevPosY,Random.Range(minZ + 1.5f,maxZ - 1.5f));  //waypoints are generated based on random unit sphere + ( bounds of the plane they are on )
Vector3 relative = transform.InverseTransformPoint (waypoint);
float angle = Mathf.Atan2 (relative.x, relative.z) * Mathf.Rad2Deg;

I know how it works in a normal 2D coordinate system, however when switching to a 3D coordinate system, if I would want to move my character on the x-z plane, then how does this actually work mathematically?

I am assuming that it would be the angle between z and x axis? so in a mathematical equation would it be, angle = Atan2(z/x) or Atan2(x/z)? Would both of them work?

\$\endgroup\$
3
\$\begingroup\$

Beware of the argument order here. Here is what atan2 will give you:

  • atan2(x,z) is the angle between the (x,0,z) vector and the +Z axis in the Z-X plane.
  • atan2(z,x) is the angle between the (x,0,z) vector and the +X axis in the X-Z plane.
\$\endgroup\$
1
\$\begingroup\$

The value of the angle variable would be equivalent to the atan(relative.x/relative.z) for the angles ​​lying in the range (-pi/2; +pi/2). In other words it is an angle measured from axis z, positive direction of that is a CCW rotation seen from the top of the y vector.

For the given example, the value of the angle variable would be an angle between the local (corresponding to the transform variable) z axis and a projection of the weypoint onto the local x-z plane.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.