平稳地将对象移动到目标Unity3D

时间:2019-03-21 20:39:09

标签: c# unity3d

我整天试图将对象从 A点移动到 B 点,所以我尝试了 Lerp MoveTowards SmoothDamp ,但每次对象刚从A点消失并立即出现在B点!

我尝试了在互联网上找到的所有解决方案,但是得到了相同的结果。

您能救我一命并帮助我解决这个问题吗?

这是我尝试过的代码:

    transform.position = Vector3.SmoothDamp(transform.localPosition, Destination, ref velocity, Speed);

transform.position = Vector3.Lerp(transform.localPosition, Destination, Speed);

transform.position = Vector3.MoveTowards(transform.localPosition, Destination, Speed);

还有更多...

2 个答案:

答案 0 :(得分:2)

您需要使用Lerp不断更新位置。您可以按照以下步骤使用协程进行此操作(假设已定义起点和终点):

public IEnumerator moveObject() {
    float totalMovementTime = 5f; //the amount of time you want the movement to take
    float currentMovementTime = 0f;//The amount of time that has passed
    while (Vector3.Distance(transform.localPosition, Destination) > 0) {
        currentMovementTime += Time.deltaTime;
        transform.localPosition = Vector3.Lerp(Origin, Destination, currentMovementTime / totalMovementTime);
        yield return null;
    }
}

您可以通过以下方式将此协程称为:

StartCoroutine(moveObject());

答案 1 :(得分:2)

尝试一下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SmoothMove : MonoBehaviour 
{
    public float speed = 0.01f;
    private Vector3 destination;

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

    void Update()
    {
        transform.position = Vector3.Lerp(transform.position, destination, speed)
    }

    void SetDestination(Vector3 newPos)
    {
        destination = newPos;
    }
}

希望对您有帮助。