对象未正确朝其他对象位置移动-Vector3.MoveTowards

时间:2019-07-03 04:08:21

标签: c# unity3d vector move

我正在尝试使save的变换位置移向场景中游戏对象instance的变换位置。

问题:这段代码的作用是将PointCopy轻拂到instance大约一秒钟,然后返回其原始位置。如何使PointCopy平稳地移向instance的位置,并在其完成移动后保持在原处?

这是产生PointCopy的代码。它被放置在名为“ SpawnToLerp”的场景中的空游戏对象上。

instance

PointCopy的代码为空白或默认值。 我发现如果将代码using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawntoLerp : MonoBehaviour { public GameObject CubePrefab; public GameObject instance; public PointCopy PointCopy; //i want to move instance position to PointCopy position void Start() { instance = Instantiate(CubePrefab, transform.position, transform.rotation) as GameObject; } void Update() { instance.transform.position = Vector3.MoveTowards (transform.position, PointCopy.transform.position, 5f * Time.deltaTime); } } 放在public Transform transform;的顶部,结果是相同的。

1 个答案:

答案 0 :(得分:0)

在{p1中将transform.position替换为instance.transform.position

 instance.transform.position = Vector3.MoveTowards
    (transform.position, PointCopy.transform.position, 5f * Time.deltaTime);

您所做的是使用transform中的SpawntoLerp,因此您永远不会比5f * Time.deltaTime离开该位置。

相反,您想从instance的当前位置继续前进

instance.transform.position = Vector3.MoveTowards
    (instance.transform.position, PointCopy.transform.position, 5f * Time.deltaTime);

然后您可以再次使用简单的public Transform

public class SpawntoLerp : MonoBehaviour
{
    // you can use any Component as field
    // and Unity will automatically take the according reference
    // from the GameObject you drag in
    public Transform CubePrefab;
    public Transform instance;

    // Do not call it transform as this property already exists in MonoBehaviour
    public Transform PointCopy;

    private void Start()
    {
        // instantiate automatically returns the same type
        // as the given prefab
        instance = Instantiate(CubePrefab, transform.position, transform.rotation);
    }

    private void Update()
    {
        instance.position = Vector3.MoveTowards(instance.position, PointCopy.position, 5f * Time.deltaTime);
    }
}

关于效率的更好解决方案是改用Coroutine,因为一旦达到该位置,您就不再希望移动:

public class SpawntoLerp : MonoBehaviour
{
    public Transform CubePrefab;
    public Transform PointCopy;

    private void Start()
    {
        StartCoroutine(SpawnAndMove(CubePrefab, PointCopy.position));
    }

    private IEnumerator SpawnAndMove(GameObject prefab, Vector3 targetPosition)
    {
        Transform instance = Instantiate(CubePrefab, transform.position, transform.rotation);

        while(Vector3.Distance(instance.position, targetPosition) > 0)
        {
            instance.position = Vector3.MoveTowards(instance.position, targetPosition, 5f * Time.deltaTime);

            // "Pause" the routine, render this frame and 
            // continue from here in the next frame
            yield return null;
        }
    }
}