x


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);
}
more ▼

asked Jan 05 '10 at 10:35 PM

James gravatar image

James
45 3 3 8

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. Instead, simply calculate and apply the Horizontal input in FixedUpdate.

Jan 05 '10 at 11:19 PM Ehren
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Jan 05 '10 at 11:06 PM

Ehren gravatar image

Ehren
4.2k 34 43 77

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5081
x1874
x1792

asked: Jan 05 '10 at 10:35 PM

Seen: 2825 times

Last Updated: Jan 05 '10 at 10:35 PM