[Unity] 使用Mathf函数实现平滑移动物体的7种方法

 Unity中要利用Mathf中的函数实现物体的平滑运动,有以下7种方法:

//使用Mathf.PingPong()函数在初始位置和X=311之间往复运动
rectTransform.anchoredPosition = 
new Vector2(Mathf.PingPong(
Time.time * 100, 311), rectTransform.anchoredPosition.y);
//物体就像乒乓球一样,在X轴上往复运动

//使用Mathf.Repeat()函数在初始位置和X=311之间循环移动
rectTransform.anchoredPosition = 
new Vector2(Mathf.Repeat(
Time.time * 100, 311), 0);
//与PingPong()的区别是,Repeat()函数只会沿着一个方向移动,
//到达目标位置后会直接回到初始位置

//使用Mathf.Lerp()函数移动到X=311的位置
rectTransform.anchoredPosition = 
new Vector2(Mathf.Lerp(
rectTransform.anchoredPosition.x, 311, 0.01f), 
rectTransform.anchoredPosition.y);
//逐渐减速的运动,无限接近目标值,但永远无法达到
//可以配合IF条件来达到目标位置

//使用Mathf.LerpUnclamped()函数移动到X=311的位置
rectTransform.anchoredPosition = 
new Vector2(Mathf.LerpUnclamped(
rectTransform.anchoredPosition.x, 311, 1.1f), 
rectTransform.anchoredPosition.y);
//类似使用Mathf.Lerp()函数移动
//与Mathf.Lerp()的区别是,不限制t的值在0到1之间
//超过0-1之间的t值会使得物体在两个位置不断闪烁

//使用Mathf.SmoothStep()函数移动到X=-780的位置
rectTransform.anchoredPosition = 
new Vector2(Mathf.SmoothStep(
rectTransform.anchoredPosition.x, -780f, 0.03f), 
rectTransform.anchoredPosition.y);
//逐渐减速的移动,移动速度取决于t
//无限接近于目标位置,但无法到达目标位置
//与Mathf.Lerp()函数非常类似,相比较起来,
//Mathf.SmoothStep()函数开始移动的比Mathf.Lerp()更快,
//但是后来移动的比Mathf.Lerp()慢
//Lerp像是线性衰减,而SmoothDamp更像是弧形衰减

//使用Mathf.MoveTowards()函数移动到X=100的位置
rectTransform.anchoredPosition = 
Vector2.MoveTowards(
rectTransform.anchoredPosition, new Vector2(
100, rectTransform.anchoredPosition.y), 50 * Time.deltaTime);
//均速运动,速度取决于maxDistanceDelta

//使用Mathf.SmoothDamp()函数移动到X=0的位置
float velocity = 0f;
rectTransform.anchoredPosition = 
new Vector2(Mathf.SmoothDamp(
rectTransform.anchoredPosition.x, 0, ref velocity, 0.25f,Mathf.Infinity), 
rectTransform.anchoredPosition.y);
//逐渐减速的运动,可以到达目标位置,到达目标位置后会在目标位置附近的一小段距离内随机运动
//到达目标位置的速度取决于smoothTime的值,越小越快
//velocity的值会随着函数的调用而改变
//velocity默认为0即可,如果设置了非0数,则移动到目标位置的误差会变大

Mathf.SmoothDamp、Mathf.Lerp、Mathf.SmoothStep三个方法非常相似,分别使用三个方法移动同一个物体的效果如图所示:

可以看出,三者均是先快后慢,但SmoothDamp方法会有一些卡顿;SmoothStep与Lerp比较起来,Mathf.SmoothStep函数开始移动的比Mathf.Lerp更快,但是后来移动的比Mathf.Lerp慢,Lerp像是线性衰减,而SmoothDamp更像是弧形衰减。

SmoothDamp方法移动没有速度的上限(速度上限可以通过参数设置),且能根据目标位置的距离来自动调整移动速度;而另外二者速度仅与参数设置有关,与目标位置无关。

如果要实现类似宠物跟随主人移动的效果,SmoothDamp方法更适合;实现摄像头跟随主角的效果,SmoothStep与Lerp可根据情况选择;要实现匀速运动,选择MoveTowards方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值