Advertisement
Muk99

CameraFollow

Jan 9th, 2015
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [AddComponentMenu("Camera/Camera Follow")]
  5.  
  6. public class CameraFollow : MonoBehaviour {
  7.  
  8.     public Transform target;
  9.     public float distance = 10.0f;
  10.     public float height = 5.0f;
  11.     public float heightDamping = 2.0f;
  12.     public float rotationDamping = 3.0f;
  13.  
  14.     void  LateUpdate ()
  15.     {
  16.         // Early out if we don't have a target
  17.         if (!target)
  18.             return;
  19.        
  20.         // Calculate the current rotation angles
  21.         float wantedRotationAngle = target.eulerAngles.y;
  22.         float wantedHeight = target.position.y + height;
  23.         float currentRotationAngle = transform.eulerAngles.y;
  24.         float currentHeight = transform.position.y;
  25.        
  26.         // Damp the rotation around the y-axis
  27.         currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
  28.        
  29.         // Damp the height
  30.         currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
  31.        
  32.         // Convert the angle into a rotation
  33.         Quaternion currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
  34.        
  35.         // Set the position of the camera on the x-z plane to:
  36.         // distance meters behind the target
  37.         transform.position = target.position;
  38.         transform.position -= currentRotation * Vector3.forward * distance;
  39.        
  40.         // Set the height of the camera
  41.         transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
  42.        
  43.         // Always look at the target
  44.         transform.LookAt (target);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement