Last active
December 30, 2024 02:04
-
-
Save unitycoder/39829fd49192a2b32282 to your computer and use it in GitHub Desktop.
Create Ortho Screen EdgeColliders2D - Collider Edge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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