Unity 判断物品是否在相机范围内

var CenterRect = new Rect(20, 20, Screen.width - 2 * 20, Screen.height - 2 * 20); // 这里的20是矩形框距离屏幕边界的距离

var screenPoint = Camera.main.WorldToScreenPoint(destinationObject.transform.position);// destinationObject 就是我们正在观察的目标物体

CenterRect.Contains(screenPoint); // 可以判断是否在矩形范围内

 

然后是绘制的方法

private void DrawScreenRect(Rect rect, Color color)
{
GL.LoadOrtho(); // GL加载正交
GL.Begin(GL.LINES);
{
mat.SetPass(0); // mat是一个材质 Material, 这里是为渲染激活pass通道
GL.Color(color); // 设置颜色
GL.Vertex3(rect.xMin / Screen.width, rect.yMin / Screen.height, 0); //  绘制左边
GL.Vertex3(rect.xMin / Screen.width, rect.yMax / Screen.height, 0); // 绘制左边

GL.Vertex3(rect.xMin / Screen.width, rect.yMax / Screen.height, 0); // 绘制上边
GL.Vertex3(rect.xMax / Screen.width, rect.yMax / Screen.height, 0); // 绘制左边

GL.Vertex3(rect.xMax / Screen.width, rect.yMax / Screen.height, 0); // 绘制右边
GL.Vertex3(rect.xMax / Screen.width, rect.yMin / Screen.height, 0); // 绘制右边

GL.Vertex3(rect.xMax / Screen.width, rect.yMin / Screen.height, 0); // 绘制下边
GL.Vertex3(rect.xMin / Screen.width, rect.yMin / Screen.height, 0); // 绘制下边

}
GL.End(); // 绘制结束
}

运行

Unity 判断物品是否在相机范围内

 

上一篇:BFS和DFS的一些例题


下一篇:Unity SRP 一:建立一个新管线