C# 寻找屏幕边界的最低y点
我在unity中使用c#,我需要计算相机的最低y位置(2D),但我只知道如何找到高度,即C# 寻找屏幕边界的最低y点,c#,unity3d,C#,Unity3d,我在unity中使用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() { s
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);
}
私有向量2屏幕边界;
void Start()
{
screenBounds=Camera.main.ScreenToWorldPoint(新矢量3(Screen.width,Screen.height,Camera.main.transform.position.z));
}
无效更新()
{
screenBounds=Camera.main.ScreenToWorldPoint(新矢量3(Screen.width,Screen.height,Camera.main.transform.position.z));
if(transform.position.y
}
我正在尝试使用此代码剥离旧对象。如果我理解正确,您希望保存相机看到的初始框并将其用作边界 如果是这样的话,那么在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;
您得到的是右上角的 屏幕空间以像素为单位定义。屏幕左下角为(0,0);右上角为(像素宽度、像素高度) 另外,我假设您的相机位置是,例如,
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");
不,请小心:
camY
将位于世界空间坐标,而高度
位于像素空间,因此这将返回错误的值!我知道凯美将进入世界空间,这不是你想要实现的吗?如果相机在世界空间中的位置太低,就删除它?如果它离开屏幕,就删除另一个对象。问题在于,您的下边框将是camY(世界空间,如2.5)-高度(像素,如1080)/2f
。。结果是低得多;)您可能还想交换符号,因为下限的值比上限的值小,这样更有意义。。。
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);
}
}