如果它们之间的距离在 Unity 中变得太远,则使用 Lerp 将对象移动到另一个对象

问题描述

我想使用 Lerp 将一个立方体 A 移动到另一个立方体 B,但前提是它们之间的距离大于 2.0f。但是由于 Lerp 应用在多个 Update() 帧中,因此在下一个 Update() 中,两个立方体之间的距离例如为 1.9,并且代码不会输入 if 语句中,立方体 A 只是停在那里。>

如何将立方体 A 移动到立方体 B?

void Start()
{
        startPos = transform.position;
}

void Update()
{
        float distance = Vector3.Distance(transform.position,nextStepPos.position);

        if (distance > 2.0f)
        {
            transform.position = Vector3.Lerp(transform.position,nextStepPos.position,speed * Time.deltaTime);
        }
         else
        {   
            transform.position = startPos;
        }
}

解决方法

我会使用 Vector3.MoveTowards 而不是 Lerp 并为此使用协程:

[SerializeField] Transform nextStepPos;
Coroutine moveToOtherCoroutine;
float moveSpeed = 1f; // world units per second

void Start()
{
    moveToOtherCoroutine = null;
}

void Update()
{
    if (distance > 2.0f)
    {
        if (moveToOtherCoroutine == null)
            moveToOtherCoroutine = StartCoroutine(DoMoveToOther());
    }
}

IEnumerator DoMovetoOther()
{
    while (true)
    {
        Vector3 newPos = Vector3.MoveTowards(transform.position,nextStepPos.position,Time.deltaTime * moveSpeed);
        transform.position = newPos;
        if (newPos == nextStepPos.position) 
        {
            break;
        } 
        yield return null;
    } 
    // If you want to allow moving to the cube on distance > 2.0f again
    // moveToOtherCoroutine = null;

    // Stuff that should happen when reach next step should happen here
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...