算法的2线相交? [英] Algorithm for intersection of 2 lines?

查看:188
本文介绍了算法的2线相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2行。其包含2点的X和Y的两条线这意味着他们都有长度。

我看到两个公式,一个使用的决定因素,一个使用正常的代数。这将是最有效的计算,什么公式看起来像?

我在使用code矩阵的一个困难时期。

这是我迄今为止,它可以更有效?

 公共静态Vector3类型相交(Vector3类型line1V1,Vector3类型line1V2,Vector3类型line2V1,Vector3类型line2V2)
    {
        // 1号线
        浮A1 = line1V2.Y  -  line1V1.Y;
        浮B1 = line1V2.X  -  line1V1.X;
        浮C1 = A1 * line1V1.X + B1 * line1V1.Y;

        // 2号线
        浮动A2 = line2V2.Y  -  line2V1.Y;
        浮B2 = line2V2.X  -  line2V1.X;
        浮C2 = A2 * line2V1.X + B2 * line2V1.Y;

        浮DET = A1 * B2  -  A2 * B1;
        如果(DET == 0)
        {
            返回null; //平行线
        }
        其他
        {
            浮X =(B2 * C1  -  B1 * C2)/​​ DET;
            浮动Y =(A1 * C2  -  A2 * C1)/ DET;
            返回新的Vector3类型(X,Y,0);
        }
    }
 

解决方案

假设你有两行的形式斧+通过= C ,你可以找到它pretty的轻松:

 浮动三角洲= A1 * B2  -  A2 * B1;
如果(增量== 0)
    抛出新的ArgumentException(线是平行的);

浮动X =(B2 * C1  -  B1 * C2)/​​△;
浮动Y =(A1 * C2  -  A2 * C1)/△;
 

从这里

I have 2 lines. Both lines containing their 2 points of X and Y. This means they both have length.

I see 2 formulas, one using determinants and one using normal algebra. Which would be the most efficient to calculate and what does the formula looks like?

I'm having a hard time using matrices in code.

This is what I have so far, can it be more efficient?

    public static Vector3 Intersect(Vector3 line1V1, Vector3 line1V2, Vector3 line2V1, Vector3 line2V2)
    {
        //Line1
        float A1 = line1V2.Y - line1V1.Y;
        float B1 = line1V2.X - line1V1.X;
        float C1 = A1*line1V1.X + B1*line1V1.Y;

        //Line2
        float A2 = line2V2.Y - line2V1.Y;
        float B2 = line2V2.X - line2V1.X;
        float C2 = A2 * line2V1.X + B2 * line2V1.Y;

        float det = A1*B2 - A2*B1;
        if (det == 0)
        {
            return null;//parallel lines
        }
        else
        {
            float x = (B2*C1 - B1*C2)/det;
            float y = (A1 * C2 - A2 * C1) / det;
            return new Vector3(x,y,0);
        }
    }

解决方案

Assuming you have two lines of the form Ax + By = C, you can find it pretty easily:

float delta = A1*B2 - A2*B1;
if(delta == 0) 
    throw new ArgumentException("Lines are parallel");

float x = (B2*C1 - B1*C2)/delta;
float y = (A1*C2 - A2*C1)/delta;

Pulled from here

这篇关于算法的2线相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆