- Home /
How can I lock a rigidbody's angular velocity to one axis?
I have a 3D environment with 2D gameplay. The player controls a rocket with rotate and thrust within the XY plane. The physics-based gameplay necessitates the rocket being a rigidbody. I want it to roll off collision models within the environment, which it does perfectly. But when I hit something at a high velocity, the rocket will be rotated on its local X or Y axis, setting it on an oblong plane rather than the XY plane of the environment.
I thought this code would keep the rotation locked to the local Z axis, but after some testing, I can still disengage the rocket from the XY plane.
rigidbody.angularVelocity = Vector3.Scale(rigidbody.angularVelocity, Vector3(0, 0, 1));
What is the answer?
Here is the current script for the rocket:
var thrust : float = 1; var turnSpeed : float = 1;
private var rotation : float;
function Update () { //"rotation" is > or < 0 based on left and right arrows, multiplied by "turnSpeed" rotation = Input.GetAxis ("Horizontal") turnSpeed Time.deltaTime; }
function FixedUpdate () { //"vert" is > 0 when the up arrow or W is pushed var vert : float = Input.GetAxis ("Vertical");
//Adds a force in the direction of the rocket's local Y+ coord when "vert" > 0, multiplied by "thrust"
if (vert > 0)
{
rigidbody.AddRelativeForce (Vector3(0, 1, 0) * thrust);
}
//Rotates rocket in local Z coord based on "rotation"
transform.Rotate (0, 0, rotation);
}
One suggestion: I'm not sure why you're getting the rotation input in Update and then applying it in FixedUpdate. I think that will cause you to overwrite the rotation a few times unnecessarily before you actually apply it in FixedUpdate. Ins$$anonymous$$d, simply calculate and apply the Horizontal input in FixedUpdate.
Answer by Ehren · Jan 05, 2010 at 11:06 PM
Use a Configurable Joint (see also the class documentation). If you attach it to your rigidbody, you can use it to limit the rotation around any of the axes. Simply set the "Angular X/Y/Z Motion" property to Locked for the axis you want to restrict.