Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To make a game object move continuously back and forth between two positions in Unity, you can use the following steps:

  1. Create an empty game object in the hierarchy and name it "MovementController".
  2. Attach a C# script to the "MovementController" game object and name it "MoveBackAndForth".
  3. In the script, create two public Vector3 variables: "startPos" and "endPos" to define the starting and ending positions of the movement.
  4. Create a public float variable "speed" to define how quickly the game object moves between the positions.
  5. In the "Update" method of the script, use the "Lerp" function to move the game object back and forth between the two positions.
  6. To make the movement continuous, use the Mathf.PingPong function to switch the start and end positions once the game object reaches the end position.

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.