Unity攝像機平滑處理跟隨

賽車遊戲中在處理攝像機平滑處理時遇到了一些問題,遂通過如下代碼可以實現平滑處理。

效果:在目標進行轉彎時,會平滑進行攝像機跟隨,而不是直接旋轉位置。

 

代碼如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SmoothFollow : MonoBehaviour
{
    public Transform target;

    public float height = 3.5f;
    public float distance = 7f;
    public float smoothSpeed = 1;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        // 目標的前方向
        Vector3 targetForward = target.forward;
        targetForward.y = 0;
        // 攝像機的前方向
        Vector3 currentForward = transform.forward;
        currentForward.y = 0;
        // 平滑移動
        Vector3 forward = Vector3.Lerp(currentForward, targetForward.normalized, smoothSpeed * Time.deltaTime);
        // 攝像機要調整的距離
        Vector3 targetPos = target.position + Vector3.up * height - forward * distance;
        // 更改攝像機的座標與朝向
        transform.position = targetPos;
        transform.LookAt(target);
    }
}

 

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