几何向量:射线与平面

     射线与平面的检测属于三维空间典型的检测算法之一,属于三维中基础实用一通百通的技术之一。

     之前我们在空间点与平面中已经大致了解了其中的概念和原理,不清楚的可以先回过去看下,空间表示法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组件用来检测,所以我们了解一下其中计算原理就好。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值