Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active December 17, 2022 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save unitycoder/39829fd49192a2b32282 to your computer and use it in GitHub Desktop.
Save unitycoder/39829fd49192a2b32282 to your computer and use it in GitHub Desktop.
Create Ortho Screen EdgeColliders2D - Collider Edge
// perspective camera, get far clip plane edges in world space (z is set to 0)
var bottomLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, 0, cam.farClipPlane));
var topLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, cam.pixelHeight, cam.farClipPlane));
var topRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, cam.pixelHeight, cam.farClipPlane));
var bottomRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, 0, cam.farClipPlane));
Debug.DrawLine(bottomLeft, topLeft, Color.red, 33);
Debug.DrawLine(topLeft, topRight, Color.green, 33);
Debug.DrawLine(topRight, bottomRight, Color.blue, 33);
Debug.DrawLine(bottomRight, bottomLeft, Color.magenta, 33);
using UnityEngine;
using System.Collections;
public class ScreenEdgeCollider : MonoBehaviour
{
void Awake ()
{
AddCollider();
}
void AddCollider ()
{
if (Camera.main==null) {Debug.LogError("Camera.main not found, failed to create edge colliders"); return;}
var cam = Camera.main;
if (!cam.orthographic) {Debug.LogError("Camera.main is not Orthographic, failed to create edge colliders"); return;}
var bottomLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, 0, cam.nearClipPlane));
var topLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, cam.pixelHeight, cam.nearClipPlane));
var topRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, cam.pixelHeight, cam.nearClipPlane));
var bottomRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, 0, cam.nearClipPlane));
// add or use existing EdgeCollider2D
var edge = GetComponent<EdgeCollider2D>()==null?gameObject.AddComponent<EdgeCollider2D>():GetComponent<EdgeCollider2D>();
var edgePoints = new [] {bottomLeft,topLeft,topRight,bottomRight, bottomLeft};
edge.points = edgePoints;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment