I’ve been trying to get an object with rigidboy, by using rigidbody.AddTorque(), to spin realistically so it’s angle matches a specific target angle stored as a Vector3. I don’t want to use Slerp because it wouldn’t be physically realistic, and I’d lose all physics benefits.
I’ve been having a ton of problems trying to achieve this, is there a way around to do this? Have anyone done it?
First of all, there’s a difference between angle and angular velocity.
Are you trying to maintain a specific orientation, or a specific angular velocity?
The concept “angle” doesn’t apply well to 3D objects, becuse their orientation can not be described only with a single value.
To spin a rigidbody object on its local up axis, this should work:
void FixedUpdate() {
rigidbody.AddTorque (transform.up * 10);
}
If you want to maintain a specific angle, you probably want to use a sort of controller to apply torques.
And um, to point an object in a specific direction (which means one axis is not controlled), you can try something like this:
void FixedUpdate() {
rigidbody.AddTorque(Vector3.Cross(transform.forward, targetDirection) * 10);
}
Haven’t tried this myself, but it should be something like that. You may need to swap the arguments to Vector3.Cross().
Actually…
Sorry or the spam.
Try this:
void FixedUpdate() {
rigidbody.AddTorque(Vector3.Cross(transform.forward, Vector3.up) - rigidbody.angularVelocity * 0.5f);
}
Verified to be correct… the angular velocity term adds a derivative term which makes it a PD controller kind of.
Actually…
Sorry or the spam.
Try this:
void FixedUpdate() {
rigidbody.AddTorque(Vector3.Cross(transform.forward, Vector3.up) - rigidbody.angularVelocity * 0.5f);
}
Verified to be correct… the angular velocity term adds a derivative term which makes it a PD controller kind of.
amazing…
Your code is so simple… but it contains a couple of things I can’t understand:
I checked the manual but I couldn’t understand what Vector3.Cross returns…
what is “lhs x rhs”?
Also, what’s the ‘f’ after 0.5?
j_y_k
July 20, 2010, 7:12pm
6
Cross() returns the cross product of the two vectors. (Google/search ‘vector cross product’ for more info.)
The ‘f’ specifies that the literal is of type ‘float’.
it just never ends does it? there’s too much to learn
thanks!
i have exact the same problem with aligning to a certain target angle.
this works way better then any of my tryouts, but it doesn’t stop rotating once i reached the target angle. how do i achieve that?
best -vlp-
OK i figured out by trying around a bit:
i’m basically doing this:
targetAngleForward = targetObject.transform.forward;
float strenght = 10.0f;
rigidbody.AddTorque((Vector3.Cross(transform.forward, targetAngleForward) - rigidbody.angularVelocity) * strenght );
which perfectly aligns my object to the targetobject’s angle, except the rotation around the forward axis (of course). but how could I also include that rotation axis in the formular?