Dtoliaferro: /* C# - TorqueStabilizer.cs */
[[Category: Physics]]
[[Category: MonoBehaviour]]
[[Category: C#]]
Author: Rune Skovbo Johansen
==Description==
This script basically implements a torque-based stabilizer.
==Usage==
Attach the script to any gameobject with a rigidbody.
==C# - TorqueStabilizer.cs==
<syntaxhighlight lang="csharp">
using UnityEngine;
using System.Collections;
public class TorqueStabilizer : 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);
// Uncomment the next line to stabilize on only 1 axis.
//torqueVector = Vector3.Project(torqueVector, transform.forward);
rigidbody.AddTorque(torqueVector * speed);
}
}
</syntaxhighlight>
[[Category: MonoBehaviour]]
[[Category: C#]]
Author: Rune Skovbo Johansen
==Description==
This script basically implements a torque-based stabilizer.
==Usage==
Attach the script to any gameobject with a rigidbody.
==C# - TorqueStabilizer.cs==
<syntaxhighlight lang="csharp">
using UnityEngine;
using System.Collections;
public class TorqueStabilizer : 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);
// Uncomment the next line to stabilize on only 1 axis.
//torqueVector = Vector3.Project(torqueVector, transform.forward);
rigidbody.AddTorque(torqueVector * speed);
}
}
</syntaxhighlight>
Leave a Reply