Unity3D 基础——使用 Mathf.SmoothDamp 函数制作相机的缓冲跟踪效果

使用 Mathf.SmoothDamp 函数制作相机的缓冲跟踪效果,让物体的移动不是那么僵硬,而是做减速的缓冲效果。将以下的脚本绑定在相机上,然后设定好 target 目标对象,即可看到相机的缓动效果。通过设定 smoothTime 的值,可以调节缓动效果的持续时间。

Mathf-SmoothDamp - Unity 脚本 APIicon-default.png?t=N7T8https://docs.unity.cn/cn/current/ScriptReference/Mathf.SmoothDamp.html

Mathf.SmoothDamp

public static float SmoothDamp (float current, float target, ref float currentVelocity, float smoothTime, float maxSpeed= Mathf.Infinity, float deltaTime= Time.deltaTime);

参数

current当前位置。
target尝试达到的目标。
currentVelocity当前速度,此值由函数在每次调用时进行修改。
smoothTime达到目标所需的近似时间。值越小,达到目标的速度越快。
maxSpeed可以选择允许限制最大速度。
deltaTime自上次调用此函数以来的时间。默认情况下为 Time.deltaTime。

1.创建 SmoothDamp 脚本

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

public class SmoothDamp : MonoBehaviour
{
    public Transform target;
    public float smoothTime = 0.3F;
    private float yVelocity = 0.0F;

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

    // Update is called once per frame
    void Update()
    {
        //缓动 y 轴上的位置
        float newPosition = Mathf.SmoothDamp(transform.position.y, target.position.y, ref yVelocity, smoothTime);
        transform.position = new Vector3(transform.position.x, newPosition, transform.position.z);
    }
}

2.绑定对象

将 SmoothDamp 脚本添加到 Main Camera 对象上;然后设置 Target 参数对象,调节 Target 对象的位置使其与 Main Camera 对象的高度不一样。

3.播放

单机播放按钮,可以看到主相机的高度缓缓移动到 Target 的高度。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值