- Home /
Hello! Was wondering how do I make an object move randomly around the screen. And if it disappears at one side of the screen, it'll appear on the other side.
I can make the object move in one direction, example falling down randomly, but how do i make it move around freely?
Please do make the codes as simple as possible since i'm quite new to unity! Any help is appreciated, thankyou!
Answer by imrankhanswati · Nov 26, 2017 at 07:53 AM
Hello @jingyeecheryl ... There is multiple ways to do this try this it might help you
boolean waiting = false;
float waitingTime = 2.0f;
float lerpTime = 5.0f;
void FixedUpdate (){
if (waiting == false)
{
LerpCube();
}
else
{
return;
}
}
void LerpCube(){
Vector3 randomPosition = Vector3 (Random.Range( 6,-6 ), Random.Range( 4, -4 ));
transform.position = Vector3.Lerp (transform.position, randomPosition, lerpTime * Time.deltaTime);
waiting = true;
yield WaitForSeconds (waitingTime );
waiting = false;}
I didn't got time to test it out so please give it try if it didn't worked then let me know....
Answer by Nishchhal · Nov 26, 2017 at 10:26 AM
Assuming the Centre of the screen is Origin.
Vector2 screenLimit = new Vector2 (yourscreenlimitX, yourscreenlimity); Vector2 screenLeftPos;
void Update() { If(transform.position.x > screenLimit.x || transform.position.x < -screen Limit.x || transform.position.y > screenLimit.y || transform.position.y < -screenLimit.y) { screenLeftPos = (Vector2)transform.position; transform.position = -screenLeftPos; } }
Hope it helps!
Your answer
![](https://koobas.hobune.stream/wayback/20220612143346im_/https://answers.unity.com/themes/thub/images/avi.jpg)