Unity 射线检测
Ray 射线
射线是一个无穷的线,开始于origin并沿着direction方向。
例;Ray ray = new Ray(new Vector3(1, 1, 1), new Vector3(0, 0, 0));
例2;Ray ray2 = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机发出一条射线,射向鼠标方向
Physics.Raycast 光线投射
Physics.Raycast与 Ray 以及 RaycastHit结合使用可以完成射线检测
Physics.Raycast的定义有很多种,常用到的参数是如下
-
origin
The starting point of the ray in world coordinates.
在世界坐标,射线的起始点。 -
direction
The direction of the ray.
射线的方向。 -
distance
The length of the ray
射线的长度。 -
hitInfo
If true is returned, hitInfo will contain more information about where the collider was hit (See Also: RaycastHit).
如果返回true,hitInfo将包含碰到器碰撞的更多信息。
例; RaycastHit hit;
Physics.Raycast(ray.origin, ray.direction * 1000, out hit); //out hit 指定 记录射线检测信息的 RaycastHit
RaycastHit 光线投射碰撞
Structure used to get information back from a raycast.
用来获取从raycast函数中得到的信息反馈的结构。参数如下
-
The impact point in world space where the ray hit the collider.
在世界空间中,射线碰到碰撞器的碰撞点。 -
The normal of the surface the ray hit.
射线所碰到的表面的法线。 -
The barycentric coordinate of the triangle we hit.
所碰到的三角形的重心坐标。 -
The distance from the ray's origin to the impact point.
从光线的原点到碰撞点的距离。 -
The index of the triangle that was hit.
碰到的三角形的索引。 -
The uv texture coordinate at the impact point.
在碰撞点的UV纹理坐标。 -
The secondary uv texture coordinate at the impact point.
碰撞点的第二个UV纹理坐标。 -
The uv lightmap coordinate at the impact point.
所在碰撞点的光照图UV坐标。 -
The Collider that was hit.
碰到的碰撞器。 -
The Rigidbody of the collider that was hit. If the collider is not attached to a rigidbody then it is null.
碰到的碰撞器的Rigidbody。如果该碰撞器没有附加刚体那么它为null。 -
The Transform of the rigidbody or collider that was hit.
碰到的刚体或碰撞器的变换。
例;