您当前的位置: 首页 >  unity
  • 4浏览

    0关注

    193博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

unity获得两条直线的交点

我寄人间雪满头丶 发布时间:2020-12-29 15:12:25 ,浏览量:4

    //获得交点
    public Vector2 GetIntersection(Vector2 lineAStart, Vector2 lineAEnd, Vector2 lineBStart, Vector2 lineBEnd)
    {
        float x1 = lineAStart.x, y1 = lineAStart.y;
        float x2 = lineAEnd.x, y2 = lineAEnd.y;

        float x3 = lineBStart.x, y3 = lineBStart.y;
        float x4 = lineBEnd.x, y4 = lineBEnd.y;

        //两向量相互垂直,返回0
        if (x1 == x2 && x3 == x4 && x1 == x3)
        {
            return Vector2.zero;
        }

        //两向量相互平行。返回0
        if (y1 == y2 && y3 == y4 && y1 == y3)
        {
            return Vector2.zero;
        }

        //两向量相互垂直,返回0
        if (x1 == x2 && x3 == x4)
        {
            return Vector2.zero;
        }

        //两向量相互平行。返回0
        if (y1 == y2 && y3 == y4)
        {
            return Vector2.zero;
        }
        float x, y;

        if (x1 == x2)
        {
            float m2 = (y4 - y3) / (x4 - x3);
            float c2 = -m2 * x3 + y3;

            x = x1;
            y = c2 + m2 * x1;
        }
        else if (x3 == x4)
        {
            float m1 = (y2 - y1) / (x2 - x1);
            float c1 = -m1 * x1 + y1;

            x = x3;
            y = c1 + m1 * x3;
        }
        else
        {
            float m1 = (y2 - y1) / (x2 - x1);
            float c1 = -m1 * x1 + y1;
            float m2 = (y4 - y3) / (x4 - x3);
            float c2 = -m2 * x3 + y3;
            x = (c1 - c2) / (m2 - m1);
            y = c2 + m2 * x;
        }

        if (IsInsideLine(lineAStart, lineAEnd, x, y) &&
            IsInsideLine(lineBStart, lineBEnd, x, y))
        {
            return new Vector2(x, y);
        }
        return Vector2.zero;
    }

    //交点是否在线以内
    private static bool IsInsideLine(Vector3 start, Vector3 end, float x, float y)
    {
        return ((x >= start.x && x = end.x && x = start.y && y = end.y && y             
关注
打赏
1648518768
查看更多评论
0.2960s