摄像机平滑跟随

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值