Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to check if object is off-screen?

Discussion in 'Scripting' started by False_Baconator, Dec 31, 2018.

  1. False_Baconator

    False_Baconator

    Joined:
    Oct 2, 2018
    Posts:
    35
    Hi! I'm trying to make a 2D, dungeon crawler, and I'm trying to make it so that if an ally is off-screen, then it will teleport to the player. unfortunately I have absolutely no idea where to even start with this, I would show you my code, but since i have no idea where to start with this, I don't have any relevant code to post. if you need to see my code, then I will post it though.

    I originally just thought i could just check the distance between the Ally and the camera but that would check if it were in a circular area within the camera, and that wouldn't work. i tried doing a bit of research, but i couldn't find anything i could understand.

    I could really use some help. Thanks in advance!

    TLDR: how do i check if an object is off-screen in my 2D game?
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    10,005
    e45240 likes this.
  3. False_Baconator

    False_Baconator

    Joined:
    Oct 2, 2018
    Posts:
    35
    Thanks, but it doesn't seem to be working, here's what i wrote,

    Code (CSharp):
    1.  
    2.     void OnBecameInvisible()
    3.     {
    4.         transform.position = Player.transform.position;
    5.     }
    6.  
    I tried it with OnBecameInvisible and OnBecameVisible, I also made sure to have the scene editor closed so that it wont mess with anything, any idea why it isn't working?
     
  4. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @False_Baconator

    If it's a dungeon crawler, why don't you just calculate tile distance to player?

    If x amount of tiles fit in X and Y directions in camera view, you can make it so that if tile distance is larger than let's say 5 in X and 3 in Y, then teleport the enemy. Although this depends on how you move your player relative to camera...


    If you don't want to experiment with tile distances, this seems to work but I haven't used it in my own experiments:
    Code (CSharp):
    1. var pos = cam.WorldToScreenPoint(transform.position);
    2.  
    3. outOfBounds = !Screen.safeArea.Contains(pos);
    4.  
    5. spriteRenderer.color = outOfBounds ? Color.red : Color.white;
    So this is just an artificial example. Sprite turns red if it's out of bounds of orthographic camera.

    You actually didn't tell, if you are using ortho or perspective camera...
     
    Last edited: Jan 1, 2019
    OutlawsGalaxy, mhmtbtn and e45240 like this.