- Home /
Trouble Rotating an Object on x-axis
I am attempting to rotate an object on the x-axis, but every time it crosses the x-y plane it rotates 180 degrees on the y axis. I'm using a Vector3 called momentum to keep track of the direction the object is moving in, and after I rotate the vector I want to rotate the object to match the vector's rotation. I'm having no trouble with the y-axis, just the x. Here's the code.
if (tup == 0){
tup = Time.time;
}
var rotation = Quaternion.AngleAxis((-1*Mathf.Log(Time.time - tup + 1)),Vector3.right);
momentum = (rotation * momentum);
transform.localRotation = Quaternion.LookRotation(momentum);
Answer by aldonaletto · Oct 16, 2011 at 02:13 AM
I suspect that the cause of your problem is the following: LookRotation accepts a 2nd paramater, upwards, that define which is the up direction of the object. If not specified - like in your case - Unity assumes Vector3.up. When your object's forward direction passes 90 or -90 degrees (relative to horizontal plane) its "head" starts becoming upside down, so Unity flips it 180 degrees around y to keep its "head" up. You could just assign the calculated rotation to transform.localRotation, if your object has zero rotation initially. If it has some initial localRotation, save it at the beginning and combine the saved value with the calculated rotation before updating localRotation:
// before start following momentum, save the initial rotation (at Start?) iniRot = transform.localRotation; .... // when calculating a new rotation: var rotation = Quaternion.AngleAxis(...); transform.localRotation = rotation * iniRot;
I changed the code to match yours and I'm still experiencing the issue. I also tried setting the second parameter of LookRotation to Vector3.forward and transform.forward to no avail. I'm running into the same problem with a rotation the follows mouse movement that looks like:
rotX = transform.localEulerAngles.x; //initializes the mouse rotation
rotY = transform.localEulerAngles.y;
...
rotY = rotY + Input.GetAxis("$$anonymous$$ouse X")*100*Time.deltaTime;
rotX = rotX - Input.GetAxis("$$anonymous$$ouse Y")*100*Time.deltaTime;
transform.localEulerAngles= new Vector3(rotX%360,rotY%360,0);