我正在尝试使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;
的顶部,结果是相同的。
答案 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;
}
}
}