几何向量:射线与平面

程序设计思路也简单,首先使用叉积计算出平面单位法向量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>(http://www.amjmh.com/v/BIBRGZ_558768/).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;
}
}
--------------------- 

猜你喜欢

转载自www.cnblogs.com/liyanyan665/p/11304781.html