我有一个脚本可以将相机移动限制在一个定义的范围内。不幸的是,它仅适用于第一台相机,而且我的游戏中最多有四台正交相机。
我无法使脚本适应多个摄像头,所以我认为最好的方法是将第一个摄像机视口的四个角点转换到世界位置,然后从世界位置回到摄影机2,3和4的视口。但是这似乎不起作用。
SpriteRenderer spriteBounds = GameObject.Find("Map").GetComponentInChildren<SpriteRenderer>();
float leftBound =0;
float rightBound =0;
float bottomBound =0;
float topBound = 0;
if((trackPlayer1 == null))
{
camPlayer1.transform.position = this.transform.position;
}
else
{
float vertExtent = camPlayer1.orthographicSize;
float horzExtent = vertExtent * (Screen.width * (camPlayer1.rect.width * 2)) / Screen.height; //I guess the problem is here... but how do I fix this??
leftBound = (float)(horzExtent - spriteBounds.sprite.bounds.size.x / 2.0f);
rightBound = (float)(spriteBounds.sprite.bounds.size.x / 2.0f - horzExtent);
bottomBound = (float)(vertExtent - spriteBounds.sprite.bounds.size.y / 2.0f);
topBound = (float)(spriteBounds.sprite.bounds.size.y / 2.0f - vertExtent);
camPlayer1.transform.position = new Vector3(Mathf.Clamp(trackPlayer1.transform.position.x, leftBound, rightBound), Mathf.Clamp(trackPlayer1.transform.position.y, bottomBound, topBound), camPlayer1.transform.position.z);
}
if((trackPlayer2 == null))
{
camPlayer2.transform.position = this.transform.position;
}
else
{
leftBound = camPlayer1.ViewportToWorldPoint(new Vector3(leftBound, 0, 0)).x;
rightBound = camPlayer1.ViewportToWorldPoint(new Vector3(rightBound, 0, 0)).x;
bottomBound = camPlayer1.ViewportToWorldPoint(new Vector3(0, bottomBound, 0)).y;
topBound = camPlayer1.ViewportToWorldPoint(new Vector3(0, topBound, 0)).y;
leftBound = camPlayer2.WorldToViewportPoint(new Vector3(leftBound, 0, 0)).x;
rightBound = camPlayer2.WorldToViewportPoint(new Vector3(rightBound, 0, 0)).x;
bottomBound = camPlayer2.WorldToViewportPoint(new Vector3(0, bottomBound, 0)).y;
topBound = camPlayer2.WorldToViewportPoint(new Vector3(0, topBound, 0)).y;
camPlayer2.transform.position = new Vector3(Mathf.Clamp(trackPlayer2.transform.position.x, leftBound, rightBound), Mathf.Clamp(trackPlayer2.transform.position.y, topBound, bottomBound), camPlayer2.transform.position.z);
}