duck

Unity 3D Torque Based LookAt

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