duck

Unity 3D physics Torque-based LookAt c#

Aug 31st, 2011
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.82 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. // @robotduck 2011
  5. // set the object's rigidbody angular drag to a high value, like 10
  6.  
  7. public class TorqueLookAt : MonoBehaviour {
  8.  
  9.     public Transform target;
  10.     public float force = 0.1f;
  11.  
  12.    
  13.     // Update is called once per frame
  14.     void Update () {
  15.    
  16.         Vector3 targetDelta = target.position - transform.position;
  17.        
  18.         //get the angle between transform.forward and target delta
  19.         float angleDiff = Vector3.Angle(transform.forward, targetDelta);
  20.                            
  21.         // get its cross product, which is the axis of rotation to
  22.         // get from one vector to the other
  23.         Vector3 cross = Vector3.Cross(transform.forward, targetDelta);
  24.  
  25.         // apply torque along that axis according to the magnitude of the angle.
  26.         rigidbody.AddTorque(cross * angleDiff * force);
  27.  
  28.        
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment