- Home /
 
Help with repositioning object to a random position in the FOV
I am a little stuck with trying to put an object back in the field of view after it has left the FOV. Currently, I can use the mouse to drag the camera around my game map from a birds eye view and what I am trying to achieve is to have a certain object reappear on the map when the player has moved the camera away from that, object. So basically re-position the object back onto the screen in a random position.
So far I am using OnBecameInvisible to detect when the object is no longer on the screen. How can I then move the object back onto the screen in a random position after the player has scrolled an x amount of distance away from it when its no longer on the screen?
Answer by Jessespike · Jul 27, 2016 at 08:05 PM
Camera has some useful function for positioning in the FOV: WorldToScreenPoint, ScreenToWorldPoint, etc.
 void SpawnOnScreen()
 {
     transform.localPosition = Camera.main.ViewportToWorldPoint(
         new Vector3(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 10f));
 }
 
               You can call this function with the OnBecomeInvisible event like you were doing:
 void OnBecameInvisible() {
     SpawnOnScreen();
 }
 
               or check each frame where the object is.
 void Update () {
     Vector3 viewportPoint = Camera.main.WorldToViewportPoint(transform.localPosition);
     if (viewportPoint.x <= 0.0f || viewportPoint.x >= 1.0f ||
         viewportPoint.y <= 0.0f || viewportPoint.y >= 1.0f)
     {
         SpawnOnScreen();
     }
 }
 
              Your answer