Unity C#脚本控制平移动作——MoveTowards()方法的使用

今天面试时碰到了一道面试题,需要完成物体平移的功能。平常项目都是傻傻地直接用Animator实现需求,今天才发现想要实现这种简单地平移的效果,直接用代码就可以了(我真傻,真的(´;︵;`) )被自己蠢死了

1、Mathf.MoveTowards

Unity - Scripting API: Mathf.MoveTowards

public static float MoveTowards(float current, float target, float maxDelta); 

Mathf.MoveTowards方法的功能是返回一个浮点数,其值为current向target靠近的一个值。靠近多少呢?由maxDelta决定。

  • 若maxDelta < 0,则返回的浮点数将从current开始远离target;
  • 若maxDelta >= target,由于返回的浮点数最大只能为target,故返回的浮点数为target;

举个例子:

i = Mathf.MoveTowards(i, 10, 4);

若 i 的初值为0,运行一次 i 的值变为4,再运行一次变为8,再运行一次变为10

2、Vector3.MoveTowards

Unity - Scripting API: Vector3.MoveTowards

public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta);

和Mathf.MoveTowards大同小异,返回的Vector3类型值取于current移向target直线距离的某处。
maxDistanceDelta就是移动的长度。

  • 若maxDistanceDelta< 0,则返回的Vector3将从current开始远离target;
  • 若maxDistanceDelta>= target,则返回最大值target;

3、与其他方法相结合

(1)与Update相结合

MoveTowards方法的精髓在于和Update结合使用。

public float yMax = 100;
public float speed = 2f;

void Update()
{
    Vector3 v = transform.localPosition;
    transform.localPosition = new Vector3(v.x, Mathf.MoveTowards(v.y, yMax, speed), v.z);
}

运行脚本,物体就会延着y轴平移,直到它在y轴方向的值达到yMax。speed越大,移动速度越快。

当然也可以speed * Time.deltaTime,可以无视帧率来决定移动速度。

Vector3.MoveTowards的写法也是大同小异:

public Vector3 vector3 = new Vector3(100, 100, 100);
public float speed = 2f;

void Update()
{
    transform.position = Vector3.MoveTowards(transform.position, vector3, speed);
}

运行脚本,物体平移至vector3位置

(2)与IEnumerator相结合

MoveTowards方法也可以和协程结合使用。

private IEnumerator IEMoveFillAmount(Image image, float speed)
{
    while (image.fillAmount < 1)
    {
        image.fillAmount = Mathf.MoveTowards(image.fillAmount, 1, speed / 100);
        yield return new WaitForSeconds(0.01f);
    }
}

上述代码的功能是使Image的fillAmount按每0.01秒增加speed / 100的速度增大,直到image.fillAmount大于等于1

4、Lerp方法

如果不想让物体做匀速运动,可以巧妙地运用Lerp方法,使物体做匀加速运动
Unity - Scripting API: Mathf.Lerp

public static float Lerp(float a, float b, float t); 

Unity - Scripting API: Vector3.Lerp

public static Vector3 Lerp(Vector3 a, Vector3 b, float t);

不过这就是其他的内容了,这里只给个思路

喜欢的话,可以点赞呦~

  • 34
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值