将 Unity 中的 2D 相机移动限制在地图的边缘

Limiting 2D camera movement in Unity to edge of my map

Link to Image

我设法计算了我的地图的边缘,但现在我需要计算它以便我的相机的边缘不超过我的地图的边缘。

我的代码如下所示:

using UnityEngine;

public class CameraMovement:MonoBehaviour {

public GameObject player;
public GameObject firstMap;
public GameObject lastMap;
private SpriteRenderer spriteRenderer1;
private SpriteRenderer spriteRenderer2;

public float smoothTimeX;
public float smoothTimeY;

public bool Bounds;

private Vector2 minCameraPos;
private Vector2 maxCameraPos;

// Use this for initialization
void Start()
{
    spriteRenderer1 = firstMap.GetComponent<SpriteRenderer>();
    spriteRenderer2 = lastMap.GetComponent<SpriteRenderer>();
}

void FixedUpdate()
{
    transform.position = new Vector3(player.transform.position.x, player.transform.position.y, transform.position.z);
}

void Update()
{
    Vector3 minCameraEdge = Camera.main.ViewportToWorldPoint(new Vector3(0, 0.5f, Camera.main.nearClipPlane)); // left edge of my camera in x
    Vector3 maxCameraEdge = Camera.main.ViewportToWorldPoint(new Vector3(1, 0.5f, Camera.main.nearClipPlane)); // right edge of my camera in x
    Vector3 minCameraHeight = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0, Camera.main.nearClipPlane)); // bottom edge of my camera in y
    Vector3 maxCameraHeight = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 1, Camera.main.nearClipPlane)); // top edge of my camera in y
    Debug.DrawLine(minCameraEdge, maxCameraEdge, Color.green); //use this to see the left & right edges of the camera update each frame
    Debug.DrawLine(minCameraHeight, maxCameraHeight, Color.green); //use this to see the top & bottom edges of the camera update each frame
    if (Bounds)
    {
        if (minCameraEdge.x < -spriteRenderer1.bounds.extents.x)
            minCameraEdge.x = -spriteRenderer1.bounds.extents.x;
        if (maxCameraEdge.x > spriteRenderer1.bounds.extents.x)
            maxCameraEdge.x = spriteRenderer1.bounds.extents.x;
        if (minCameraHeight.y < -spriteRenderer1.bounds.extents.y)
            minCameraHeight.y = -spriteRenderer1.bounds.extents.y;
        if (maxCameraHeight.y > spriteRenderer1.bounds.extents.y)
            maxCameraHeight.y = spriteRenderer1.bounds.extents.y;
    }
}

}

只需为第一个和最后一个块添加一个碰撞器,将图层更改为新的东西,在相机上放置一个盒子碰撞器,设置其视图大小,然后将其设置为仅与该图层碰撞。

您可以使用图层蒙版来确保它只与刚设置的 bounds 图层发生碰撞。

下面的代码只与第 9 层发生冲突。

var layerMask = (1 << 9);

注意这可以通过碰撞层矩阵轻松设置

编辑-项目设置-Physics(或Physics2D)

在检查器中,您可以看到哪些图层与哪些图层发生碰撞。如果你打算使用这个方法,而不是代码,你还需要在它自己的图层中设置相机,然后取消它的碰撞,除了 bounds

您可以通过选择一个对象来添加新的物理层,然后单击检查器右上角的层,然后单击添加层。