I found this script that returns rotational speed (taking into account where force is applied and distance from center of mass).
public Vector3 ForceToTorque(Vector3 force, Vector3 position, ForceMode forceMode = ForceMode.Force)
{
Vector3 t = Vector3.Cross(position - body.worldCenterOfMass, force);
ToDeltaTorque(ref t, forceMode);
return t;
}
private void ToDeltaTorque(ref Vector3 torque, ForceMode forceMode)
{
bool continuous = forceMode == ForceMode.VelocityChange || forceMode == ForceMode.Acceleration;
bool useMass = forceMode == ForceMode.Force || forceMode == ForceMode.Impulse;
if (continuous) torque *= Time.fixedDeltaTime;
if (useMass) ApplyInertiaTensor(ref torque);
}
private void ApplyInertiaTensor(ref Vector3 v)
{
v = body.rotation * Div(Quaternion.Inverse(body.rotation) * v, body.inertiaTensor);
}
private static Vector3 Div(Vector3 v, Vector3 v2)
{
return new Vector3(v.x / v2.x, v.y / v2.y, v.z / v2.z);
}
With 2100 newtons I'm getting 0.6 radians (36 degrees) of rotation.
var test = rotationScript.ForceToTorque(shipFront.right * 2100, shipFront.position, ForceMode.Force);
Debug.Log(test + " " + test * Mathf.Rad2Deg);
// Above gives (0, 0.6, 0) and (0, 36.1, 0)
But using AddForceAtPosition
to rotate the ship with the same force I don't get the same result
if (currTurn > 0) {
body.AddForceAtPosition(shipFront.right * 2100, shipFront.position, ForceMode.Force);
body.AddForceAtPosition(-shipBack.right * 2100, shipBack.position, ForceMode.Force);
} else if (currTurn < 0) {
body.AddForceAtPosition(-shipFront.right * 2100, shipFront.position, ForceMode.Force);
body.AddForceAtPosition(shipBack.right * 2100, shipBack.position, ForceMode.Force);
}
It's not giving me 36 degrees per second - I tested by counting how long it took to do a full 360 spin, supposedly it should've been done in 10s but it took 10s to rotate only ~90º.
There's a lot I don't understand in the first script, like most of the physics part, but I don't see it taking into consideration my ships mass (body.worldCenterOfMass
?), could that be it?
I need this so I can rotate my ship more precisely.