摄像机平滑跟随

来源:互联网 发布:阿尔法收益 知乎 编辑:程序博客网 时间:2024/05/27 19:26
using UnityEngine;
using System.Collections;


//更新位置的委托
delegate void UpdatePosition();

public class CameraFollow : MonoBehaviour {

    public Transform target;

    //需要锁定的坐标(无法实时生效)
    public bool freazeX, freazeY, freazeZ;


    //跟随的平滑时间(类似于滞后时间)
    public float smoothTime = 0.3f;
    private float xVelocity, yVelocity, zVelocity = 0.0f;

    private Vector3 offset;

    //全局缓存的位置变量
    private Vector3 oldPosition;

    private Vector3 startPosition;

    private UpdatePosition JudgePosition;


    void Start ()
    {
        startPosition = transform.position;
        offset = transform.position - target.position;

        //事件
        if (!freazeX)
        {
            JudgePosition += MoveX;
        }
        if (!freazeY)
        {
            JudgePosition += MoveY;
        }
        if (!freazeZ)
        {
            JudgePosition += MoveZ;
        }
    }

   void LateUpdate ()
    {
        oldPosition = transform.position;
        JudgePosition();

        transform.position = oldPosition;    

   }

  
    private void MoveX()
    {
        //Mathf.SmoothDamp(三个重载):   Gradually changes a value towards a desired goal over time.
        //current:          The current position.
        //target:           The position we are trying to reach.
        //currentVelocity: The current velocity, this value is modified by the function every time you call it.
        //smoothTime:    Approximately the time it will take to reach the target. A smaller value will reach the target faster.
        //maxSpeed:     Optionally allows you to clamp the maximum speed.
        //deltaTime:     The time since the last call to this function. By default Time.deltaTime.
        oldPosition.x = Mathf.SmoothDamp(transform.position.x, target.position.x + offset.x, ref xVelocity, smoothTime);
    }


    private void MoveY()
    {
        oldPosition.y = Mathf.SmoothDamp(transform.position.y, target.position.y + offset.y, ref yVelocity, smoothTime);
    }


    private void MoveZ()
    {
        oldPosition.z = Mathf.SmoothDamp(transform.position.z, target.position.z + offset.z, ref zVelocity, smoothTime);
    }


    /// <summary>
    /// 用于重新开始游戏时重置相机位置
    /// </summary>
    public void ResetPosition()
    {
        transform.position = startPosition;
    }
}
0 0