几何向量(11):射线与平面

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


     之前我们在空间点与平面中已经大致了解了其中的概念和原理,不清楚的可以先回过去看下,空间表示法A*x+B*y+C*z+D = 0,射线表示法为start + n*dir(起点+模长*朝向),那么射线与平面检测,就是解方程组就好了,还是画个图方便理解,如下:

707.png

程序设计思路也简单,首先使用叉积计算出平面单位法向量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;
    }
}

效果如如下:

570.gif

当然unity中提供了我们Ray和Raycast组件用来检测,所以我们了解一下其中计算原理就好。


      

————————————————

版权声明:本文为CSDN博主「羊羊2035」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/yinhun2012/article/details/97886462



本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

会员中心
搜索
«    2024年4月    »
1234567
891011121314
15161718192021
22232425262728
2930
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864