Search code examples
unity-game-enginecameracollision

Unity 2d collision with the edge of the camera


I'm not sure if the title is correct. I'm new to unity and I'm trying to make a simple (2D) pong. The problem is that I'm trying to do something different from tutorials, I want the ball to collide with the edges of the screen. Of course I can simply put an object and give it a collider and put manually at the edge, but is there a way to make the ball collide with the edge of the camera? Thanks!


Solution

  • I think that there are 2 things you can try (if you don't want to add 4 colliders around your area) and the first thing you need to understand is that the camera is not actually in the position you are watching in-game view, it is just a projection. The camera is probably way behind so you are not searching for a collision with the Camera but a collision with what the Camera sees.

    1. ADDING AN EDGE COLLIDER

    The edge collider simply puts a collider around the edges of an object, but it won't work like that because the camera is far behind and so you will need to scale a bit the collider to fit the actual game view.

    1. ADDING A CODE THAT DOES THIS

    This is a bit stupid but can work, I mean, it is way easier to add 4 colliders but I guess you can do it with code and get same result. For example if I want the top border I can use:

    GameObject top;
    void Awake()
     {
         top = new GameObject("Top");
     }
    
    
    void Start()
    {
    BoxCollider2D collider = top.AddComponent<BoxCollider2D>();
         collider.size = new Vector3(Mathf.Abs(Camera.main.ScreenToWorldPoint(new Vector3(0f, 0f, 0f)).x - Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0f)).x), 0.1f, 0f);
         collider.offset = new Vector2(collider.size.x / 2f, collider.size.y / 2f);
    
         top.transform.position = new Vector3((Camera.main.ScreenToWorldPoint(new Vector3(0f, 0f, 0f)).x - Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0f)).x) / 2f, Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0f)).y, 0f);
    }
    

    I think this is just a bit dumb to do, because this is just for the top collider, and maybe you should consider a way to work in the inspector with them