查找屏幕边界的最低y点



我使用的是统一的c#,我需要计算相机的最低y位置(2D(,但我只知道如何找到高度,即

private Vector2 screenBounds;

void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));      
}

void Update()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));

if (transform.position.y < screenBounds.y)
Destroy(this.gameObject);
}

}

我正试图用这个代码来清除旧物体。

您得到的是右上角

屏幕空间是以像素为单位定义的。屏幕的左下角是(0,0(;右上角为(pixelWidth,pixelHeight(。

我还假设你的相机位置是例如z = -10,你想要一个世界点在相机的前面而不是后面

因此,如果你想要底部边界,你宁愿使用

screenBounds = Camera.main.ScreenToWorldPoint(new Vector3 (0, 0, -Camera.main.transform.position.z);

如果您的相机是正交,那么您根本不必关心z,只需使用即可

screenBounds = Camera.main.ScreenToWorldPoint(Vector2.zero);

为了不必计算两次,如果你稍后还想检查它是否在屏幕上方,你也可以反过来,尽管这通常更容易:

// Other than the ScreenToWorldPoint here it doesn't matter whether 
// the camera is orthogonal or perspective or how far in front of the camera you want a position
// or if your camera is moved or rotated
var screenPos = Camera.main.WorldToScreenPoint(transform.position);
if(screenPos.y < 0) Debug.Log("Below screen");
else if(screenPos.y > Screen.height) Debug.Log("Above screen");
if(screenPos.x < 0) Debug.Log("Left of screen");
else if(screenPos.x > Screen.width) Debug.Log("Right of screen");

但是,仅使用transform.position有点不可靠,因为您已经破坏了仍然(一半(可见的对象。

相反,你可以使用GeometryUtility.CalculateFrustumPlanes来获得实际相机截头体周围的平面,然后使用GeometryUtility.TestPlanesAABB来检查你的对象的Renderer.bounds是否真的对相机可见,例如

Renderer _renderer;
Camera _camera;
void Update()
{
if(!_renderer) _renderer = GetComponent<Renderer>();
if(!_camera) _camera = Camera.main;
var planes = GeometryUtility.CalculateFrustumPlanes(_camera);
if (!GeometryUtility.TestPlanesAABB(planes, _renderer.bounds))
{
Debug.Log($""{name}" is outside of the screen!", this);
// and e.g.
Destroy(gameObject);
}
}

如果我理解正确,你想保存相机看到的初始框并将其用作边界吗?

如果是这样的话,那么在2D中很容易做到,但在3D中会变得复杂得多。下面是2D解决方案。

摄影机位于视口的中心。这意味着顶部边界是摄影机位置加上视口高度的一半。

// Get the camera height
float height = Screen.height;
// Now we get the position of the camera
float camY = Camera.Main.transform.position.y;
// Now Calculate the bounds
float lowerBound = camY + height / 2f;
float upperBound = camY - height / 2f;

最新更新