Hi
I’m building a 3D game and I want to add torque in a direction. unity Rigidbody.AddTorque function is using axes.
My question is how to translate a direction to axes?
The game roughly goes like this:
You control a ball that’s rolling around (like in the official Unity beginner’s tutorials) but when you hit an object (of any shape!) the gravity is supposed to be in the direction perpendicular to the surface that the ball is touching.
I have something working, and the ball “sticks” to any surface and can be rolled around on it.
But the controls are not relative to the camera, like I want them to.
I want the ball to go left (from my point of view) when I press left and so on.
Any ideas how to achieve this?
This method might help.
using UnityEngine;
public static partial class ExtRigidbody
{
public static void MoveRotationTorque(this Rigidbody rigidbody, Quaternion targetRotation, ForceMode forceMode, float speed)
{
if(speed == 0) speed = 1;
Quaternion rotation = targetRotation * Quaternion.Inverse(rigidbody.rotation);
rigidbody.AddTorque((new Vector3(rotation.x, rotation.y, rotation.z) * speed) / Time.fixedDeltaTime, forceMode);
rigidbody.angularVelocity = Vector3.zero;
}
}
You can play around with that and see if it works out. Use it like this…
myRigidbody.MoveRotationTorque(targetRotation, ForceMode.VelocityChange, 1);
If you dont have a target rotation, but have a target direction, than maybe you can use the Quaternion.LookRotation method to convert the direction to a rotation.
This method is not perfect, as it is basically constantly changing. You will notice this more the higher you set the speed, the object will start to jitter.