Unity小游戏——移动的小船船(摄影机跟随船体移动)

关键功能:

  1. 摄影机跟随船体移动
  2. 船体在水面上晃动
  3. 摇杆控制方向

摄影机跟随对象的原理:

每一帧的开始的时候,都先去把这个摄影机移动到和对象相同的位置,然后收集跟随对象旋转的角度,然后将摄影家挪到对象的后面,在想上挪动一段距离,这个时候,摄影机就到了对象后面靠上,并一直跟着对象。

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
  
public class CameraFollow : MonoBehaviour  
{  
// 这个是我们跟随的对象
    public new GameObject gameObject;  
  
    // Start is called before the first frame update  
    void Start()  
    {  
          
    }  
  
    // Update is called once per frame  
    void Update()  
    {  
        if(gameObject == null)  
        {  
            return;  
        }  
  	// 将摄影机的位置挪到我们跟随对象的位置
        this.transform.position = gameObject.transform.position;  
  	// 然后我们将摄影机此时的位置取出来,便于我们操作
        Vector3 CameraPosition = this.transform.position;  
// 取出来四元数,这个四元数是由我们跟随的物体在绕着Y轴旋转的角度对应的欧拉角
        Quaternion rotation = Quaternion.Euler(0,gameObject.transform.eulerAngles.y,0);  
// 然后我们将摄影机向后移动四个单位,然后在乘以这个四元数,此时就是向后平移和旋转的操作都进行之后的结果,这个结果代表移动之后的摄影机的座标。
        CameraPosition += rotation * Vector3.back * 4;  
// 摄影机向上移动一个单位
        CameraPosition.y += Vector3.up.z;  
// 将我们更改之后的座标给摄影机,让摄影机直接复制过去
        this.transform.position = CameraPosition;  
  	// 让我们的摄影机看着我们跟随的物体
        this.transform.LookAt(gameObject.transform);  
    }  
}  

Github:https://github.com/YuDang1024/UnityGames/tree/master/MovingBoat

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章