Jul
26
2015

Create Orthographic Screen EdgeColliders2D

screen_edge_collider_unity

Small snippet for adding EdgeCollider2D along screen edges. (for orthographic camera).
Add script to empty gameobject (at position 0,0,0). *My camera was at 0,0,-10


// 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);

view raw

ScreenEdge.cs

hosted with ❤ by GitHub


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;
}
}

 

 


1 Comment + Add Comment

Leave a comment

Connect

Twitter View LinkedIn profile Youtube Github Join Discord Twitch Instagram BlueSky

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.