unity3d中的Mathf.SmoothDamp函数的使用学习笔记!!

今天开始看android开发范例中的第三个范例,这里注意到这个函数Mathf.SmoothDamp的使用,游戏中用于做相机的缓冲跟踪,我们其实会留意一些游戏使用了smoothmove的功能,其实就是类似的效果,只是发现这个函数很容易的已经分装好了,查了官网文档发现使用起来真的非常简单。

smoothdamp,我的理解是平滑缓冲,东西不是僵硬的移动而是做减速缓冲运动到指定位置。我们看看代码:

1 2 3 4 5 6 7 8 public Transform target; //The player public float smoothTime= 0.3f; //Smooth Time private Vector2 velocity; //Velocity void Update () { //Set the position transform.position = new Vector3(Mathf.SmoothDamp(transform.position.x, target.position.x, ref velocity.x, smoothTime),Mathf.SmoothDamp( transform.position.y, target.position.y, ref velocity.y, smoothTime),transform.position.z); }
1 2 3 4 5 6 7 8 public Transform target; //The player public float smoothTime= 0.3f; //Smooth Time private Vector2 velocity; //Velocity void Update () { //Set the position transform.position = new Vector3(Mathf.SmoothDamp(transform.position.x, target.position.x, ref velocity.x, smoothTime),Mathf.SmoothDamp( transform.position.y, target.position.y, ref velocity.y, smoothTime),transform.position.z); }

这里稍微做一下讲解,target(跟踪的目标)、smoothtime(缓冲时间,时间越大缓冲速度越慢,移动也越慢)、velocity(相对缓冲减速,看起来很屌很复杂,事实上我们根本不用理睬他,它只是用作一个承载变量,我们只要默认赋值其实就是0就可以了)。

在update中,本物体(其实就是camera)的移动至做x轴和y轴移动,因为是横版游戏嘛~,大家其实可以吧velocity直接指定成一个float值,直接使用就是了。

好吧,大概讲解到此,希望帮到各位~

经验分享 程序员 微信小程序 职场和发展