Reputation: 167
I am making a 2D game in Unity, and in this game, the camera will not need to move. As such, I would like to constrain the player's movement within the camera border, preferably with collision instead of just based on the player's transform. Honestly, I have no idea where to start doing something like this, but I assume it would involve some scripting. I am pretty comfortable with scripting at this point, but if your answer includes scripting, I would appreciate it if it would include thorough explanations of everything that is going on. By the by, I am using C#.
Upvotes: 2
Views: 5837
Reputation: 20259
If the camera is in orthographic mode, you can use EdgeCollider2D
to do this, finding the world positions of the corners of the screen using ScreenToWorldPoint
to then determine the shape of the EdgeCollider2D
.
The Unity Community UnityLibrary Github has an example (copied below):
// adds EdgeCollider2D colliders to screen edges
// only works with orthographic camera
using UnityEngine;
using System.Collections;
namespace UnityLibrary
{
public class ScreenEdgeColliders : 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;
}
}
}
Upvotes: 4