Ask Your Question
2

How to make a game object move continuously back and forth between two positions in Unity?

asked 2021-09-07 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-09-01 00:00:00 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-07 11:00:00 +0000

Seen: 11 times

Last updated: Sep 01 '22