1 | initial version |
To make a game object move continuously back and forth between two positions in Unity, you can use the following steps:
Here is an example code for the "MoveBackAndForth" script:
public class MoveBackAndForth : MonoBehaviour { public Vector3 startPos; public Vector3 endPos; public float speed;
void Update()
{
float pingPong = Mathf.PingPong(Time.time * speed, 1.0f);
transform.position = Vector3.Lerp(startPos, endPos, pingPong);
if (pingPong >= 0.999f)
{
Vector3 tempPos = startPos;
startPos = endPos;
endPos = tempPos;
}
}
}
Note: you can set the "startPos" and "endPos" vectors in the Inspector window by dragging and dropping game objects or typing in the values manually.