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

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

Mathf-SmoothDamp - Unity 脚本 APIhttps://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 脚本

cs 复制代码
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 的高度。

相关推荐
Clank的游戏栈1 小时前
Unity多线程渲染指令队列设计与集成技术详解
windows·unity·游戏引擎
Thomas_YXQ8 小时前
Unity3D IK解算器技术分析
开发语言·搜索引擎·unity·全文检索·unity3d·lucene
星火撩猿17 小时前
常见游戏引擎介绍与对比
unity·ue5·游戏引擎·godot
sky_smile_Allen17 小时前
[Unity]-[UI]-[Prefab] 关于Unity UGUI 的布局及组件讲解
ui·unity·游戏引擎
太妃糖耶1 天前
URP-利用矩阵在Shader中实现物体的平移和缩放
unity·矩阵
是阿根1 天前
unity使用iTextSharp生成PDF文件
unity·c#·游戏引擎
常城2 天前
Unity中通过TMP使用图片字体
unity·游戏引擎
惊鸿醉2 天前
⭐Unity 开发 | 如何通过 NTP 网络时间实现精准的跨平台时间同步【附完整源码 + UI 模块 + 偏差分析】
网络·unity·游戏引擎
海鸥-w2 天前
Unity中使用Cinemachine插件创建自由视角相机(freelookCamera)来实现第三人称漫游
数码相机·unity·游戏引擎
EQ-雪梨蛋花汤2 天前
【Unity笔记】Unity音效管理:ScriptableObject配置 + 音量控制 + 编辑器预览播放自动化实现
笔记·unity·编辑器