射线与平面的检测属于三维空间典型的检测算法之一,属于三维中基础实用一通百通的技术之一。
之前我们在空间点与平面中已经大致了解了其中的概念和原理,不清楚的可以先回过去看下,空间表示法A*x+B*y+C*z+D = 0,射线表示法为start + n*dir(起点+模长*朝向),那么射线与平面检测,就是解方程组就好了,还是画个图方便理解,如下:
程序设计思路也简单,首先使用叉积计算出平面单位法向量PN,然后根据射线start和dir求解模长n,就得到相交Point了,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayPlaneTest : MonoBehaviour
{
public Transform Plane;
public Transform Start;
public Transform End;
private Mesh mesh;
private Vector3 endPos;
void Awake()
{
mesh = Plane.GetComponent<MeshFilter>().sharedMesh;
endPos = End.position;
}
void Update()
{
End.position = endPos + new Vector3(Mathf.Sin(Time.time) * 0.2f, 0, 0);
Vector3 p = Plane.TransformPoint(mesh.vertices[0]);
Vector3 p1 = Plane.TransformPoint(mesh.vertices[1]);
Vector3 p2 = Plane.TransformPoint(mesh.vertices[2]);
Vector3 s = Start.position;
Vector3 e = End.position;
Vector3 point = GetRayPlanePoint(p, p1, p2, s, e);
#if UNITY_EDITOR
Debug.DrawLine(s, point, Color.red);
#endif
}
private Vector3 GetRayPlanePoint(Vector3 p, Vector3 p1, Vector3 p2, Vector3 start, Vector3 end)
{
Vector3 cross = Vector3.Cross(p1 - p, p2 - p);
Vector3 dir = (end - start).normalized;
#if UNITY_EDITOR
Debug.DrawLine(p, p + cross, Color.black);
Debug.DrawLine(start, start + dir, Color.black);
#endif
float u = cross.x;
float v = cross.y;
float w = cross.z;
float a = p.x;
float b = p.y;
float c = p.z;
float Sx = start.x;
float Sy = start.y;
float Sz = start.z;
float dx = dir.x;
float dy = dir.y;
float dz = dir.z;
float n = ((u * a + v * b + w * c) - (u * Sx + v * Sy + w * Sz)) / (u * dx + v * dy + w * dz);
return start + n * dir;
}
}
效果如如下:
当然unity中提供了我们Ray和Raycast组件用来检测,所以我们了解一下其中计算原理就好。