- Home /
Rotate Rigidbody to Rotation Via AngularVelocity
Hello all,
I'm looking to get a rigidbody object to align its rotation with another object by moving the rigidbody via angular velocity/forces. The rigidbody is not effected by gravity and is motionless in space.
Here's a breakdown of what I'm trying to achieve:
Object A has a rigidbody
Object B is a gameobject with a rotation
Object A (Rigidbody) should add/set its angular velocity so its rotation matches Object B.
The rotation can be gradual.
The rotation is not limited to any axis; the object can rotate freely.
I'm really not great at rotations/quaternions and this is giving me a lot of problems.
Any help is much appreciated.
Thank you!
try this code:
float dir = Vector3.Cross(A.transform.forward, B.transform.forward).y;
A.GetComponent<Rigidbody>().angularVelocity = new Vector3(0f, Vector3.Dot(A.transform.forward, B.transform.forward)*dir, 0f) * lerpSpeed;
adjust lerpSpeed to change how quickly it matches the rotaion of B.
Hey, thanks for your response.
I gave your code a try and it works great, but it only rotates around the y axis. I tried implementing rotation for the other axes and while it worked at first, it becomes inaccurate at more extreme rotations.
Okey, you are right,
other solution i can think of is this,
void FixedUpdate(){
// if this doesn't work try "B.transform.eulerAngles - A.transform.eulerAngles" below
Vector3 difference = A.transform.eulerAngles - B.transform.eulerAngles;
Vector3 velocity = difference / Time.fixedDeltaTime;
A.rigidbody.angularVelocity = velocity;
}