- Home /
The question is answered, right answer was accepted
How to stabilize angular motion (alignment) of hovering object?
How do I stabilize the angular motion of a hovering object? I have a hovering vehicle that moves at some distance above the ground, controlled with the arrows keys. The problem is that when it collides with some object (like a building) its rotation gets shifted. When I am moving it after this, it moves according to its local space rotation.
How can I cause my Rigidbody to return back to its initial rotation where it is only rotated around the Y axis?
Answer by runevision · Jan 21, 2010 at 01:34 PM
You can use this script (C#) to stabilize your Rigidbody so it returns to an alignment where the local Y axis points upwards:
using UnityEngine; using System.Collections;
public class HoverStabilizer : MonoBehaviour {
public float stability = 0.3f;
public float speed = 2.0f;
// Update is called once per frame
void FixedUpdate () {
Vector3 predictedUp = Quaternion.AngleAxis(
rigidbody.angularVelocity.magnitude * Mathf.Rad2Deg * stability / speed,
rigidbody.angularVelocity
) * transform.up;
Vector3 torqueVector = Vector3.Cross(predictedUp, Vector3.up);
rigidbody.AddTorque(torqueVector * speed * speed);
}
}
With the script you can control both how fast the Rigidbody stabilizes and how stable or wobbly the stabilization is.
Note: If you only want to stabilize along one axis, you can project the torqueVector onto that axis. For example, to stabilize along the local z (forward) axis only, do this before applying the torque:
torqueVector = Vector3.Project(torqueVector, transform.forward);
wow, ok this totally corrected the issue I was having described here:
http://forum.unity3d.com/threads/206015-how-to-add-torque-to-correct-bank
by projecting the predicted vector onto the right axis!.. I just spent two days trying to understand Quaternions... my head is literally spinning in confusion.
Answer by Sasmaster · Jan 21, 2010 at 01:54 PM
Thank you so much . I am still quite new to 3d math in unity so i am having a hard time to figure out this stuff . Before your solution I actually decided to use Configurable Joint and cancel out angular x,z but the downside of it was that on collisions there was no angular change at all that have made these collisions to look unrealistic . Now that is exactly what I need .
Thanks once again !!!!!!!
You're welcome! :) Consider in the future to add comments like this using "add comment" to the answer you're commenting on, rather than adding it as a new answer (because your comment is not an answer to the posted question).