问题
In the inspector for a gameObject I'm using the starting rotation is "-90", but when I run print(transform.eulerAngles.x)
I get 270 (ditto for transform.localEulerAngles.x
).
If I tilt the gameObject
downward, the inspector X value gets bigger (say, to -85) as it should. The printed transform.eulerAngles.x
also gets bigger, say to 274.
Here's where things get weird:
If I tilt the gameObject
upward the inspector x coordinate gets smaller (ex, to -95), as it should, BUT the printed eulerAngle.x
value gets BIGGER (here to 274). So if I rotate the object up or down from the eulerAngle.x
being 270, the x value increases regardless.
I'm definitely doing something wrong here, but after a lot of troubleshooting I still can't figure out what. Any thoughts?
回答1:
eulerAngles are a convoluted process in Unity3D. You should never increment/decrement or set the values in your inspector or via code. Should only use absolute values to read and set it.
Don't increment or decrement the values, as it will fail when the angle exceeds 360 degrees. Transform.Rotate is what you use instead.
Here is the sample code in the Unity3D documentation example:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public float yRotation = 5.0F;
void Update() {
yRotation += Input.GetAxis("Horizontal");
transform.eulerAngles = new Vector3(10, yRotation, 0);
}
void Example() {
print(transform.eulerAngles.x);
print(transform.eulerAngles.y);
print(transform.eulerAngles.z);
}
}
This is taken directly from the documentation: https://docs.unity3d.com/ScriptReference/Transform-eulerAngles.html
Also Transform.Rotate documentation: https://docs.unity3d.com/ScriptReference/Transform.Rotate.html
The inspector will almost always give you a funky value vs when you log it. The only consistency you will get is print(transform.rotation). This should retain similar values across inspector and code.
回答2:
for each value in transform.eulerAngles
or transform.localEulerAngles
if it has a parent:-
if (value > 270)
value =- 360;
来源:https://stackoverflow.com/questions/38509472/unity3d-eulerangles-local-and-global-totally-different-than-whats-in-inspec