How to detect camera edge collision unity?

In this article, we will see how to detect camera edge collision in unity 2D through C#.

Before I share the script, Let me tell you that this solution is only for 2D Games. So if you still need it, you can continue reading.

So the ultimate idea is we create a Collider on the edges of the camera so our player or enemy or any of your entities can detect that yes this is the end of the screen.

Detect camera edge collision
Detect camera edge collision

Detect camera edge collision

Required things for this to work:-

  1. The camera projection-type should be orthographic.
  2. This is script must be attached to the camera.

So here is the C# script for detecting the Mobile or any screen camera corners detection so you can write your logic whenever you collide with camera edges. And Let me tell you that it is responsive to any kind of resolution For Mobile, iPad, Desktop/PC.

using UnityEngine;

public class CameraEdgeCollision : MonoBehaviour
{
    private void Awake()
    {
        AddColliderOnCamera();
    }

    public void AddColliderOnCamera()
    {
        if(Camera.main == null)
        {
            Debug.LogError("No camera found make sure you have tagged your camera with 'MainCamera'");
            return;
        }

        Camera cam = Camera.main;

        if(!cam.orthographic)
        {
            Debug.LogError("Make sure your camera is set to orthographic");
            return;
        }

        // Get or Add Edge Collider 2D component
        var edgeCollider = gameObject.GetComponent<EdgeCollider2D>() == null ? gameObject.AddComponent<EdgeCollider2D>() : gameObject.GetComponent<EdgeCollider2D>();

        // Making camera bounds
        var leftBottom = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, 0, cam.nearClipPlane));
        var leftTop = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, cam.pixelHeight, cam.nearClipPlane));
        var rightTop = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, cam.pixelHeight, cam.nearClipPlane));
        var rightBottom = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, 0, cam.nearClipPlane));

        var edgePoints = new[] { leftBottom, leftTop, rightTop, rightBottom, leftBottom };

        // Adding edge points
        edgeCollider.points = edgePoints;
    }
}

So this is how we can detect camera edge collision in unity 2D.

Hope it was helpful, Let me know if you have any other issues or queries you can contact me through social media.

You can also find my youtube video on the same topic

Leave a Comment

Your email address will not be published.