当前位置:网站首页>在Unity中判断游戏物体是否在游戏屏幕范围之内
在Unity中判断游戏物体是否在游戏屏幕范围之内
2022-08-10 05:35:00 【三和尚】
在Unity中判断游戏物体是否在游戏屏幕范围之内
public bool IsInView(Vector3 worldPos)
{
//获得游戏场景中主摄像机的Transfrom引用
Transform camTransform = Camera.main.transform;
//将传过来的世界坐标转化为游戏屏幕坐标
Vector2 viewPos = Camera.main.WorldToViewportPoint(worldPos);
//将坐标进行规范化
Vector3 dir = (worldPos - camTransform.position).normalized;
//判断物体是否在相机前面
float dot = Vector3.Dot(camTransform.forward, dir);
if (dot > 0 && viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1)
return true;
else
return false;
}
void Update()
{
//因为屏幕看起来就像是二维坐标一样,所以要将游戏物体的世界坐标转化为游戏屏幕的二维坐标
Vector2 vec2 = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);
if (IsInView(transform.position))
{
Debug.Log("目前本物体在摄像机范围内");
}
else
{
Debug.Log("目前本物体不在摄像机范围内");
}
}
注意:要把这个脚本绑定在这个要进行判断的游戏物体上!
边栏推荐
猜你喜欢
随机推荐
.Net Core imports tens of millions of data to Mysql
LeetCode 1720.解码异或后的数组(简单)
样条曲线(下)之插值问题(贝塞尔曲线、B样条和一般样条曲线插值)
【接口自动化】
LeetCode 1894. Find the student number that needs to be supplemented with chalk
接口自动化2.0
pytorch-06.逻辑斯蒂回归
PyTorch 之 可视化网络架构
Test of the opposite sex what you look like?
pytorch-11.卷积神经网络(高级篇)
pytorch-11. Convolutional Neural Network (Advanced)
Radon 变换原理和应用
Deep learning TensorFlow entry environment configuration
.Net Core导入千万级数据至Mysql
机器学习——聚类——商场客户聚类
pytorch-10. Convolutional Neural Networks
LeetCode 2011. Variable Value After Action (Simple)
51单片机AD590温度测量ADC0832运放2.73V减法电压变换
程序员副业赚钱之道,实现月收入增加20K
树结构——2-3树图解