I simply want the edge of my screen to act as a collider no matter what the size. Is there a simple way I can do this?
This is about the goofiest thing I have ever created, but it does work. I am using an Orthographic camera with BoxColliders2D (I have no idea if you are doing 2D or not). It essentially wraps the screen with 4 colliders.
Add it to a gameobject in the scene and it should do everything for you.
using UnityEngine;
public class ScreenColliderManager : MonoBehaviour
{
GameObject top;
GameObject bottom;
GameObject left;
GameObject right;
void Awake()
{
top = new GameObject("Top");
bottom = new GameObject("Bottom");
left = new GameObject("Left");
right = new GameObject("Right");
}
void Start()
{
CreateScreenColliders();
}
void CreateScreenColliders()
{
Vector3 bottomLeftScreenPoint = Camera.main.ScreenToWorldPoint(new Vector3(0f, 0f, 0f));
Vector3 topRightScreenPoint = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0f));
//// Create top collider
BoxCollider2D collider = top.AddComponent<BoxCollider2D>();
collider.size = new Vector3(Mathf.Abs(bottomLeftScreenPoint.x - topRightScreenPoint.x), 0.1f, 0f);
collider.offset = new Vector2(collider.size.x / 2f, collider.size.y / 2f);
top.transform.position = new Vector3((bottomLeftScreenPoint.x - topRightScreenPoint.x) / 2f, topRightScreenPoint.y, 0f);
// Create bottom collider
collider = bottom.AddComponent<BoxCollider2D>();
collider.size = new Vector3(Mathf.Abs(bottomLeftScreenPoint.x - topRightScreenPoint.x), 0.1f, 0f);
collider.offset = new Vector2(collider.size.x / 2f, collider.size.y / 2f);
//** Bottom needs to account for collider size
bottom.transform.position = new Vector3((bottomLeftScreenPoint.x - topRightScreenPoint.x) / 2f, bottomLeftScreenPoint.y - collider.size.y, 0f);
// Create left collider
collider = left.AddComponent<BoxCollider2D>();
collider.size = new Vector3(0.1f, Mathf.Abs(topRightScreenPoint.y - bottomLeftScreenPoint.y), 0f);
collider.offset = new Vector2(collider.size.x / 2f, collider.size.y / 2f);
//** Left needs to account for collider size
left.transform.position = new Vector3(((bottomLeftScreenPoint.x - topRightScreenPoint.x) / 2f) - collider.size.x, bottomLeftScreenPoint.y, 0f);
// Create right collider
collider = right.AddComponent<BoxCollider2D>();
collider.size = new Vector3(0.1f, Mathf.Abs(topRightScreenPoint.y - bottomLeftScreenPoint.y), 0f);
collider.offset = new Vector2(collider.size.x / 2f, collider.size.y / 2f);
right.transform.position = new Vector3(topRightScreenPoint.x, bottomLeftScreenPoint.y, 0f);
}
}
Another solution would be to add an edge colider to the main camera, and then editing the colider to the edge of the camera window, so that it scales with the size of the screen. Probably easier than writing out a script. @Kingdomkey6677