Thursday, June 30, 2016

unity - How to rotate object just like in the scene?


Look at this image, I selected an object and pivot is set to local:


enter image description here


When I rotated selected object in the scene by X axis, it rotates exactly I wanted.


enter image description here


But if I rotate axis from inspector or script, it doesn't rotated to desired angle.


I'm not sure, but it seems it's related about Quaternion, but everything I tried doesn't worked well.


How do I rotate that object just like in rotated from scene?




Answer



The (local) transform gizmo shows you rings of possible rotations from the current orientation, about the current local x, y, and z axes respectively.


The Inspector / transform.localEulerAngles property show you the current local orientation expressed as Tait-Bryan angles (commonly called Euler angles) with x, y, and z components.


These are not the same thing.


Tait-Bryan angles are not a point in rotation space. They're directions for how to get there. In Unity's formulation, they say:




  1. Starting from the default/identity orientation





  2. Rotate y degrees clockwise around your local y+ axis
    (note that this turns the local x & z axes)




  3. Next, rotate x degrees clockwise around your new local x+ axis
    (note that this turns the local y & z axes)




  4. Finally, rotate z degrees clockwise around your new local z+ axis





So the y rotation always happens first and z rotation always happens last. (If you think of the rotations as local-space. If you think of them in parent space, the order is reversed but the result is the same)


But using the transform gizmo, you can grab & turn the green & blue rings in any order you want, or even interleave them. Three numeric fields aren't enough to specify this kind of interleaving, at least not alone.


If you want to get the result of turning the green (y+) gizmo in local mode no matter what orientation you're starting from, in code you can write any of these equivalent expressions:



  • transform.Rotate(Vector3.up, yawAngle)

  • transform.Rotate(0, yawAngle, 0);

  • transform.Rotate(transform.up, yawAngle, Space.World);

  • transform.rotation = transform.rotation * Quaternion.AngleAxis(yawAngle, Vector3.up)



  • transform.rotation = transform.rotation * Quaternion.Euler(0, yawAngle, 0)




  • transform.rotation = Quaternion.AngleAxis(yawAngle, transform.up) * transform.rotation;




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...