Unity 簡單的第三人稱視角


  攝像機跟隨目標移動,並在水平和垂直方向做平滑處理

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class ThirdControl: MonoBehaviour {
 5          public Transform target;//要跟隨的目標
 6          public float distance=8.0f;//攝像機離目標的距離
 7          public float height=5.0f;//攝像機離目標的高度
 8          public float heihtDamping=0.3f;//水平跟隨平滑系數
 9          public float rotationDamping=0.3f;//跟隨高度變化系數
10          public float refRotation=0f;
11          public float refHeight=0f;
12 
13          void LateUpdate(){
14                if(target){
15                       float targetRotationAngle=target.eulerAngles.y;//目標的朝向
16                       float targetHeight=target.position.y+height;//得到跟隨的高度
17 
18                       float cameraRotationAngle=transform.eulerAngles.y;//攝像機的朝向
19                       float cameraHeight=transform.position.y;//攝像機的高度
20        
21                       cameraRotationAngle=Mathf.SmoothDampAngle(cameraRotationAngle,targetRotationAngle,ref refRotation,rotationDamping);//從攝像機目前的角度變換到目標的角度
22                      
23                       cameraHeight=Mathf.SmoothDamp(cameraHeight,targetHeight,ref refHeight,heightDamping);//從攝像機目前的高度平滑變換到目標的高度
24 
25                        Quaternion cameraRotation=Quternion.Euler(0,cameraRotationAngle,0);//每幀在Y軸上旋轉攝像機 旋轉的角度為cameraRotationAngle 因為上面的代碼已經得到了每幀要從攝像機當前的角度變換到目標角度cameraRotationAngle
26 
27                        //下面幾句代碼主要設置攝像機的位置
28                        transform.position=target.position;
29                        transform.position-=cameraRotation*Vecotr3.forward*distance;
30                        transform.position=new Vector3(transform.position.x,cameraHeight,transform.position.z);
31 
32                        //使攝像機一直朝着目標方向
33                        transform.LookAt(target);
34                }
35          }
36 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM