我这个摄像机是跟随角色,且角色朝向某个方向,镜头也会做相应的调整,我看网上大部分估计66%左右只是设置镜头和角色之间的offset,并没有考虑角色可能一直在寻找敌人,攻击敌人或者跑向敌人的时候,他们没有去考虑摄像机是否转向的问题

using UnityEngine;
namespace XX.Battle // 这里命名空间隐藏掉 ,xx你可以自己替换你想要的
{

    public class CameraFollow : MonoBehaviour
    {
        public Transform target;            // The position that that camera will be following.
        public float smoothing = 5f;        // The speed with which the camera will be following.


        public float height = 8f;
        public float offx = 5f;
        Vector3 offset;                     // The initial offset from the target.
       
        public void Init()  // 当你给相机,通常是场景相机添加这个脚本的时候 接下来调用init ,为什么不在start中去做,

// 其实也可以但是我觉得程序员通过代码直接调用的形式更好,而且start的调用你看不到堆栈。
        {
            // Calculate the initial offset.
            //快速出个方案 然后做ai的丰富去 
            var dir = transform.position - target.position;
            var cosxita = Vector3.Dot(dir.normalized, (-target.forward).normalized); 
            var distance = Vector3.Distance(transform.position, target.position); // 3d空间两者的距离
            offx = distance * cosxita;  //xz平面上 两者的距离 
            height = dir.y; // 摄像机的相对高度 
        }
        

        void LateUpdate() 
        {
            if (target == null)
            {
                return;
            }

//对偏移量进行插值计算,每帧进来它就更接近结果一些           

offset = Vector3.Lerp(offset, (-target.forward) * offx, smoothing * Time.deltaTime);
            offset.y = height;
            // Create a postion the camera is aiming for based on the offset from the target.
            Vector3 targetCamPos = target.position + offset;

            // 如果下面继续使用插值,摄像机就会抖动。
            transform.position = targetCamPos;// Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);
            transform.LookAt(target);
        }
    }
}

 

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐