Created
January 13, 2015 05:11
-
-
Save stefanhayden/65a5bf62b29ef160ca76 to your computer and use it in GitHub Desktop.
Unity C# - TorqueLookRotation2D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
// @stefanhayden 2015 | |
// based on http://wiki.unity3d.com/index.php/TorqueLookRotation | |
// set the object's rigidbody angular drag to a high value, like 10 or 50 | |
public class TorqueLookRotation : MonoBehaviour { | |
public Transform target; | |
public float force = 0.1f; | |
void FixedUpdate () { | |
Vector3 targetDelta = target.position - transform.position; | |
//get the angle between transform.forward and target delta | |
float angleDiff = Vector3.Angle(transform.up, targetDelta); | |
// get its cross product, which is the axis of rotation to | |
// get from one vector to the other | |
Vector3 cross = Vector3.Cross(transform.up, targetDelta); | |
// apply torque along that axis according to the magnitude of the angle. | |
rigidbody.AddTorque(cross.z * angleDiff * force); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment