- Home /
Use RigidBody.AddTorque with Quaternions or Forward/Up/Right vectors?
I need to use the AddTorque function to "push" a RigidBody towards a specific angle. Last time I tried to do this I spent several days, failed, and gave up. I've come back to this problem because I really want to make this game.
What I am trying to do is this, copied from my less-specific Stack Overflow question:
I'm trying to play an animation on a humanoid bone structure and, using torque (rotational force), push the physics ragdoll into approximately the same pose as the bone structure.
So far I've been assuming that I need to convert my Quaternion rotation to a Euler angle in order to use it with AddTorque, but some helpful guy on Stack Overflow pointed out that the function doesn't actually work directly with Euler angles. This got me thinking.
My question is this: Is it possible to use RigidBody.AddTorque with either Quaternion rotations or the Forward/Up/Right vectors of the transform to "push" a rigidbody toward a specific angle (this specific angle being stored as a Quaternion)? The obvious way is to get the Euler angles out of the Quat, but this is unreliable and the physics tends to spaz severely.
I'd appreciate any help on this :)
Answer by Clonkex · Jun 15, 2014 at 01:08 AM
Some awesome guy from Stack Overflow solved my problem for me :D I posted an answer, because he worked it out entirely in the comments:
Answer by HiddenMonk · May 28, 2015 at 07:03 AM
Using the answer from the stackoverflow post above, I was able to make this.
using UnityEngine;
public static partial class ExtRigidbody
{
public static void MoveRotationTorque(this Rigidbody rigidbody, Quaternion targetRotation)
{
rigidbody.maxAngularVelocity = 1000;
Quaternion rotation = targetRotation * Quaternion.Inverse(rigidbody.rotation);
rigidbody.AddTorque(rotation.x / Time.fixedDeltaTime, rotation.y / Time.fixedDeltaTime, rotation.z / Time.fixedDeltaTime, ForceMode.VelocityChange);
rigidbody.angularVelocity = Vector3.zero;
}
}
I haven't worked on this project for some considerable time now so I can't tell off the top of my head if this code would work, but assu$$anonymous$$g it does this could be very helpful to some people. Thanks for posting :)
This mostly works, but because it only uses 3 of the 4 components of the quaternion, it goes awry in some edge cases. Try multiplying the torque vector by rotation.w, e.g.
var torque = new Vector3(rotation.x, rotation.y, rotation.z) * rotation.w * Time.fixedDeltaTime;
Oh my god THANK YOU! Now my torque doesn't try to take a shortcut!
Your answer
Follow this Question
Related Questions
Quaternion.euler gives me glitch. Why? 1 Answer
Weird rotation behaviour 1 Answer
Gun not rotating with the camera? 1 Answer
Quaternion.Slerp problem... 1 Answer