Camera2DFollow官方脚本解析

using System;
using UnityEngine;

namespace UnityStandardAssets._2D
{
    public class Camera2DFollow : MonoBehaviour
    {
        public Transform target;    //欲跟随的目标
        public float damping = 1;   //镜头到达时间
        public float lookAheadFactor = 3;   //镜头偏移量
        public float lookAheadReturnSpeed = 0.5f;   //镜头回转速度
        public float lookAheadMoveThreshold = 0.1f;
        public float offset = 3;    //镜头与角色距离

        private float m_OffsetZ;    //z轴偏移量
        private Vector3 m_LastTargetPosition;   //上一帧的位置
        private Vector3 m_CurrentVelocity;  //当前速度  
        private Vector3 m_LookAheadPos;     //前方位置

        // Use this for initialization
        private void Start()
        {
            m_LastTargetPosition = target.position; //初始化上一帧位置
            m_OffsetZ = (transform.position - target.position).z;   //初始化z轴偏移量  
            transform.parent = null;    //设置摄像机的父级物体为空
        }


        // Update is called once per frame
        private void Update()
        {


            float xMoveDelta = (target.position - m_LastTargetPosition).x;  //计算每帧在x轴的偏移量

            //判断是否改变方向或加速
            bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;    

            // 只在改变方向和加速时更新前方位置
            if (updateLookAheadTarget)  
            {   
                //前方位置 = 镜头偏移量 * 角色朝向
                m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
            }
            else
            {
                //如果角色未运动,缓慢改变前方位置坐标为(0,0,0).

                //Vector3.MoveTowards函数基本上和Vector3.Lerp相同,而是该函数将确保我们的速度不会超过maxDistanceDelta。
                //maxDistanceDelta的负值从目标推开向量,就是说maxDistanceDelta是正值,当前地点移向目标,如果是负值当前地点将远离目标。
                m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
            }

            //目标前方位置 = 目标位置 + 前方位置 + z轴偏移
            Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;

            /*
            我们来看下这个函数   Vector3.SmoothDamp 平滑阻尼
            SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime) 

            current             当前的位置
            target              我们试图接近的位置
            currentVelocity     当前速度,这个值由你每次调用这个函数时被修改
            smoothTime          到达目标的大约时间,较小的值将快速到达目标
            maxSpeed            选择允许你限制的最大速度
            deltaTime           自上次调用这个函数的时间。默认为Time.deltaTime
            */

            Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);

            //将新位置赋给镜头位置
            transform.position = newPos;

            //更新目标位置
            m_LastTargetPosition = target.position;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值