【Unity】常见对象移动方法

1 前言

        记录下常见的游戏对象移动API。

2 移动API

2.1 MoveTowards

Vector3.MoveTowards

代码:

using UnityEngine;

public class Move : MonoBehaviour
{
    Vector3 targetPos;//定义目的地
    private void Awake()
    {
        //初始化目的地
        targetPos = this.transform.localPosition;
        targetPos.z += 10.0f;
    }
    void Update()
    {
        //匀速运动。
        //返回新的位置,在每帧,将新位置赋值给当前对象,即可实现移动。
        //提供三个参数:当前位置、目标位置、最大移动距离。
        this.transform.localPosition = Vector3.MoveTowards(this.transform.localPosition, targetPos, Time.deltaTime * 3.0f);
    }
}

演示:

2.2 SmoothDamp

Vector3.SmoothDamp

        此API存在一个问题:永远无法到达目标点。所以需要进行判断,在靠近目标点一定程度时,直接将对象设置到目标点处。

代码:

using UnityEngine;

public class Move : MonoBehaviour
{
    Vector3 targetPos;//定义目的地
    Vector3 speed;//定义速度
    private void Awake()
    {
        //初始化目的地
        targetPos = this.transform.localPosition;
        targetPos.z += 10.0f;
        //初始化速度
        speed = Vector3.zero;
    }
    void Update()
    {
        //阻尼运动,慢增慢减的平滑效果。
        //返回新的位置,在每帧,将新位置赋值给当前对象,即可实现移动。
        //可提供五个参数:当前位置、目标位置、用于维护的速度、平滑时间、最大速度。
        //速度:此速度是需要一直维护的,所以不能是局部变量,建议全局变量,此API会根据速度来计算新位置。
        //平滑时间:并不是移动时间,而是用于调整平滑效果的,可以手动测试,选择合适的值。
        this.transform.localPosition = Vector3.SmoothDamp(this.transform.localPosition, targetPos, ref speed, 2.0f, 100.0f);
    }
}

演示:

2.3 Lerp

Vector3.Lerp

        这只是个插值API,实际并不是为了移动而提出的,但也能用。
        此API在减速移动情况下(t为小数值),永远无法到达目标点。所以需要进行判断,在靠近目标点一定程度时,直接将对象设置到目标点处。不过在匀速移动情况下(t最终为1),则可以到达目标点。

代码:

using UnityEngine;

public class Move : MonoBehaviour
{
    Vector3 targetPos;//定义目的地
    private void Awake()
    {
        //初始化目的地
        targetPos = this.transform.localPosition;
        targetPos.z += 10.0f;
    }
    void Update()
    {
        //使用插值实现运动。可匀速、可阻尼。
        //返回新的位置,在每帧,将新位置赋值给当前对象,即可实现移动。
        //提供三个参数:值a、值b、插值比t。
        //返回值为a + (b - a) * t。
        this.transform.localPosition = Vector3.Lerp(this.transform.localPosition, targetPos, Time.deltaTime);//此调用方式是减速效果
    }
}

演示:

匀速调用:

代码:

using UnityEngine;

public class Move : MonoBehaviour
{
    Vector3 startPos;//定义起始位
    Vector3 targetPos;//定义目的地
    float time;//计时,用作插值比t
    float timeControl = 0.5f;//用于控制移动时间
    private void Awake()
    {
        //初始化
        startPos = this.transform.localPosition;
        targetPos = this.transform.localPosition;
        targetPos.z += 10.0f;

    }
    void Update()
    {
        //累计时间,计时
        time += Time.deltaTime;
        //当time * timeControl = 1时,此时time的值即为移动到目标点所需的时间。如这里,所需时间即为2s。
        this.transform.localPosition = Vector3.Lerp(startPos, targetPos, time * timeControl);//匀速
    }
}

演示:

3 结束语

        代码只是API的演示。具体使用应考虑细节问题。如:无法到达目标点时,判断差距然后设置对象到目标点;还有什么到达目标点后应在update中停止调用;或是使用协程来移动对象,到达终点后结束协程。

猜你喜欢

转载自blog.csdn.net/Davidorzs/article/details/134930571