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.
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
Asked: 2021-09-07 11:00:00 +0000
Seen: 11 times
Last updated: Sep 01 '22
How can values in R be renamed when they need to be truncated at various positions?
What is the maximum number of emails one can send per day using Google Apps Script?
How can a Qt application detect a trigger triggered by a batch script?
Why does the import of a dependency fail in a Node.js script when running inside a Docker container?
What is the process for utilizing environment variables in the package.json script through .env?
If the take profit or stop loss is reached, do the entries exit on the next bar in Pine Script?