几何向量:二维射线与直线相交

      刚好用到二维射线与直线相交,顺便记录一下。
      问题如下:
在这里插入图片描述
      二维平面中存在射线bp和直线ac,计算bp与ac的交点p1,计算原理很简单,通过直线方程组求解即可,如下:
在这里插入图片描述      将射线bp和直线ac的方程参数k1、k2、d1、d2计算出来,再计算二元一次方程组就能得到结果。
      下面测试一下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayLineCross : MonoBehaviour
{
    public Transform A;
    public Transform B;
    public Transform C;
    public Transform P;

    void Start()
    {

    }

    void Update()
    {
        Vector2 a = A.position;
        Vector2 b = B.position;
        Vector2 c = C.position;
        Vector2 p = P.position;
        Vector2 p1 = GetRayLineCrossPoint(a, b, c, p);
#if UNITY_EDITOR
        Debug.LogFormat("RayLineCross p1 = {0}", p1);
        Debug.DrawLine(a, c, Color.white);
        Debug.DrawLine(b, p, Color.white);
        Debug.DrawLine(p, p1, Color.red);
#endif
    }

    private Vector2 GetRayLineCrossPoint(Vector2 a, Vector2 b, Vector2 c, Vector2 p)
    {
        float Xa = a.x, Ya = a.y, Xb = b.x, Yb = b.y, Xc = c.x, Yc = c.y, Xp = p.x, Yp = p.y;

        float k1 = (Yp - Yb) / (Xp - Xb);
        float d1 = Yb - k1 * Xb;

        float k2 = (Yc - Ya) / (Xc - Xa);
        float d2 = Ya - k2 * Xa;

        float x = (d2 - d1) / (k1 - k2);
        float y = k1 * x + d1;

        return new Vector2(x, y);
    }
}

      效果如下:
在这里插入图片描述
      计算正确,OK,有时间继续。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值