1 using UnityEngine;
2
3 namespace
UnityStandardAssets.Utility
4 {
5     
public class SmoothFollow : MonoBehaviour
6     {
7
8         
// The target we are following
9         
[SerializeField]
10         
private Transform target;
11         
// The distance in the x-z plane to the target
12         
[SerializeField]
13         
private float distance = 10.0f;
14         
// the height we want the camera to be above the target
15         
[SerializeField]
16         
private float height = 5.0f;
17
18         
[SerializeField]
19         
private float rotationDamping;
20         
[SerializeField]
21         
private float heightDamping;
22
23         
// Use this for initialization
24         
void Start() { }
25
26         
// Update is called once per frame
27         
void LateUpdate()
28         {
29             
// Early out if we don't have a target
30             
if (!target)
31                 
return;
32
33             
// Calculate the current rotation angles
34             
var wantedRotationAngle = target.eulerAngles.y;
35             
var wantedHeight = target.position.y + height;
36
37             
var currentRotationAngle = transform.eulerAngles.y;
38             
var currentHeight = transform.position.y;
39
40             
// Damp the rotation around the y-axis
41             currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
42
43             
// Damp the height
44             currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);
45
46             
// Convert the angle into a rotation
47             
var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
48
49             
// Set the position of the camera on the x-z plane to:
50             
// distance meters behind the target
51             transform.position = target.position;
52             transform.position -= currentRotation * Vector3.forward * distance;
53
54             
// Set the height of the camera
55             transform.position =
new Vector3(transform.position.x ,currentHeight , transform.position.z);
56
57             
// Always look at the target
58             transform.LookAt(target);
59         }
60     }
61 }


Xem tìm kiếm...