针对单个对象的有效光线碰撞检测
光线在Unity中对于实现碰撞和UI交互非常有用. 官方文档提供了使用它们的典型方法:
RaycastHit hit;
浮动距离= 0;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0F)) {
//确定哪个对象正在使用hit.对撞机,对它做点什么
}
检测所有击中物体的等效方法是:
RaycastHit[] hits;
hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
However, 如果我们只是想看看一个特定的物体是否挡住了光线呢, 而不是一一列举, 我们不确定(或者不在乎)它是否会大受欢迎? 我们可以通过从它的边界开始而不是从射线开始来检查单个物体, using the Bounds.IntersectsRay
method:
Ray ray = ... // our ray
GameObject go = ... // our game object
Collider collider = go.GetComponent();
if (collider.bounds.IntersectsRay(ray)) {
// object hit!
}
这也可以与 Bounds
object provided by a MeshRenderer
.