Link to Image
我设法计算了地图的边缘,但是现在我需要进行计算,以使相机的边缘不超过地图的边缘。
我的代码如下所示:
using UnityEngine;
公共课程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);
请注意,可以通过碰撞层矩阵轻松设置
编辑项目设置-物理(或Physics2D)
在检查器中,您可以看到哪些层与哪些层碰撞。如果要使用此方法而不是代码,则还需要将相机设置在其自己的图层中,然后取消除
bounds
以外的所有内容的碰撞您可以通过以下方式添加新的物理层:选择一个对象,然后单击检查器右上角的层,然后单击“添加层”。