我是Unity的新手。我想将一个物体从一个地方移动到另一个地方,然后再自动返回第一个地方。有没有办法做到这一点?这是我移动对象的代码,但它无限超越!
float speedX = 1; float speedY = 0; float speedZ = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate (new Vector3 (speedX, speedY, speedZ) * Time.deltaTime);
}
答案 0 :(得分:0)
它无法正常工作,因为您只是将对象转换为同一方向而没有任何限制停止。一种方法是使用Lerp将位置值从一个点插值到另一个点。 http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
下面的代码将gameObject从p1移动到p2,然后返回到p1;
public Transform p1, p2;
public float speed = 1.0f;
private float startTime;
private float journeyLength;
bool isMovingForward = true;
float threshold = 0.001f;
void Start () {
startTime = Time.time;
journeyLength = Vector3.Distance(p1.position, p2.position);
}
void Update () {
if (isMovingForward && Mathf.Abs((transform.position - p2.position).sqrMagnitude) < (threshold * threshold)){
isMovingForward = false;
startTime = Time.time;
}
float distCovered = (Time.time - startTime) * speed;
float fracJourney = distCovered / journeyLength;
if (isMovingForward)
transform.position = Vector3.Lerp(p1.position, p2.position, fracJourney);
else
transform.position = Vector3.Lerp(p2.position, p1.position, fracJourney);
}