Calculate rotations to look at a 3D point?

前端 未结 4 1772
生来不讨喜
生来不讨喜 2020-12-07 17:55

I need to calculate the 2 angles (yaw and pitch) for a 3D object to face an arbitrary 3D point. These rotations are known as \"Euler\" rotations simply because after the fir

4条回答
  •  一整个雨季
    2020-12-07 18:33

    Here are my working assumptions:

    • The coordinate system (x,y,z) is such that positive x is to the right, positive y is down, and z is the remaining direction. In particular, y=0 is the ground plane.
    • An object at (0,0,0) currently facing towards (0,0,1) is being turned to face towards (x,y,z).
    • In order to accomplish this, there will be a rotation about the x-axis followed by one around the y-axis. Finally, there is a rotation about the z-axis in order to have things upright.

    (The terminology yaw, pitch, and roll can be confusing, so I'd like to avoid using it, but roughly speaking the correspondence is x=pitch, y=yaw, z=roll.)

    Here is my attempt to solve your problem given this setup:

    rotx = Math.atan2( y, z )
    roty = Math.atan2( x * Math.cos(rotx), z )
    rotz = Math.atan2( Math.cos(rotx), Math.sin(rotx) * Math.sin(roty) )
    

    Hopefully this is correct up to signs. I think the easiest way to fix the signs is by trial and error. Indeed, you appear to have gotten the signs on rotx and roty correct -- including a subtle issue with regards to z -- so you only need to fix the sign on rotz.

    I expect this to be nontrivial (possibly depending on which octant you're in), but please try a few possibilities before saying it's wrong. Good luck!


    Here is the code that finally worked for me.

    I noticed a "flip" effect that occurred when the object moved from any front quadrant (positive Z) to any back quadrant. In the front quadrants the front of the object would always face the point. In the back quadrants the back of the object always faces the point.

    This code corrects the flip effect so the front of the object always faces the point. I encountered it through trial-and-error so I don't really know what's happening!

     rotx = Math.atan2( y, z );
     if (z >= 0) {
        roty = -Math.atan2( x * Math.cos(rotx), z );
     }else{
        roty = Math.atan2( x * Math.cos(rotx), -z );
     }
    

提交回复
热议问题