I’m trying to rotate a rigidbody on the Y-axis using MoveRotation , Input “Horizontal” and time, but cannot see where this is breaking.
Steps :
make a target rotation , make it equal to this.transform.[current rotation in degrees]
increase or decrease target rotation’s Y (in degrees) by Input “Horizontal” and deltaTime
‘snap to target rotation - euler angles degrees’ with rigidbody.MoveRotation(target rotation);
Script :
var targetRotAngle : Quaternion = Quaternion.Euler (0, 0, 0);
var turnSpeed : float = 10.0;
function FixedUpdate () {
targetRotAngle = Quaternion.Euler (0, transform.eulerAngles.y, 0);
targetRotAngle.y += Input.GetAxis("Horizontal") * Time.deltaTime * turnSpeed;
rigidbody.MoveRotation(targetRotAngle);
}
Pretty much, ‘targetRotAngle’ is a Quaternion, not a 3-axis rotation. Quaternions are to complex numbers what complex numbers are to real numbers, but don’t let that worry you- all you really need to know is that anything you can’t do with the inbuilt Quaternion library, you should ask a mathematician about. Modifying the values directly- right out. Don’t do it unless you really understand what quaternions are.
Just because it’s created with the ‘.Euler’ factory, doesn’t mean it’s a euler angle on the inside.
As @syclamoth said, the quaternion components x,y and z have nothing to do with the familiar Euler angles - don’t mess with them directly!
I would use a trick similar to that used in Orient vehicle to ground normal: keep the desired angle about Y in a variable, and assign Quaternion.Euler(0, angle, 0) to transform.rotate - or pass it to rigidbody.MoveRotation():
var targetRotAngle: float = 0.0;
var turnSpeed : float = 10.0;
function Update () {
targetRotAngle += Input.GetAxis("Horizontal") * Time.deltaTime * turnSpeed;
transform.rotation = Quaternion.Euler(0,targetRotAngle%360,0);
}
I moved the code to Update and used transform.rotation because Input is synced to the update cycle - reading it in FixedUpdate may cause double or triple rotation increments. If you really need to use rigidbody.MoveRotation, split the Input reading and MoveRotation:
var targetRotAngle: float = 0.0;
var turnSpeed : float = 10.0;
function Update () { // read the input in Update and apply to targetRotAngle:
targetRotAngle += Input.GetAxis("Horizontal") * Time.deltaTime * turnSpeed;
}
function FixedUpdate(){
// rotate the rigidbody in FixedUpdate:
rigidbody.MoveRotation(Quaternion.Euler(0,targetRotAngle%360,0));
}
NOTE: Pass the angle in modulo 360, since angles out of range may produce weird results.