예제 #1
0
    //计算线段是否相交
    private bool IsRectCross(Obstructer.line p1, Obstructer.line p2)
    {
        bool IsCross = !(Mathf.Max(p1.start.x, p1.end.x) < Mathf.Min(p2.start.x, p2.end.x) ||
                         Mathf.Max(p1.start.y, p1.end.y) < Mathf.Min(p2.start.y, p2.end.y) ||
                         Mathf.Max(p2.start.x, p2.end.x) < Mathf.Min(p1.start.x, p1.end.x) ||
                         Mathf.Max(p2.start.y, p2.end.y) < Mathf.Min(p1.start.y, p1.end.y));

        if (IsCross)
        {
            if ((((p1.start.x - p2.start.x) * (p2.end.y - p2.start.y) -
                  (p1.start.y - p2.start.y) * (p2.end.x - p2.start.x)) *
                 ((p1.end.x - p2.start.x) * (p2.end.y - p2.start.y) -
                  (p1.end.y - p2.start.y) * (p2.end.x - p2.start.x))) > 0 ||
                (((p2.start.x - p1.start.x) * (p1.end.y - p1.start.y) -
                  (p2.start.y - p1.start.y) * (p1.end.x - p1.start.x)) *
                 ((p2.end.x - p1.start.x) * (p1.end.y - p1.start.y) -
                  (p2.end.y - p1.start.y) * (p1.end.x - p1.start.x))) > 0)
            {
                IsCross = false;
            }
        }

#if DRAWDEBUG
        Debug.DrawLine(p1.start, p1.end, IsCross ? Color.red : Color.green);
        Debug.DrawLine(p2.start, p2.end, Color.yellow);
        if (IsCross)
        {
            // Debug.Break();
        }
#endif

        return(IsCross);
    }
예제 #2
0
    private bool CheckBoxLine(Obstructer.Rect boxRect, Vector2 dir, out Vector2 newDir)
    {
        newDir = Vector2.zero;
        if (!boxRect.Overlaps(m_PlayerRect, out m_OveRect))
        {
            return(false);
        }

        //场景碰撞盒的四条边
        m_SideLines = m_OveRect.boxLines;

#if DRAWDEBUG
        m_OveRect.DrawBox(Color.blue);
#endif

        float maxValue = m_OveRect.width > m_OveRect.height ? m_OveRect.width : m_OveRect.height;
        //检测线段
        m_DirLine = new Obstructer.line(m_OveRect.center, m_OveRect.center - dir * (maxValue * 2));

        for (int index = 0; index < m_SideLines.Length; index++)
        {
            if (IsRectCross(m_SideLines[index], m_DirLine))
            {
                //得到相交矩形的非相交轴的长度
                if (index < 2)
                {
                    newDir.y = (dir.y > 0 ? -1 : 1) * (m_OveRect.height + 0.01f);
                }
                else
                {
                    newDir.x = (dir.x > 0 ? -1 : 1) * (m_OveRect.width + 0.01f);
                }

                return(true);
            }
        }

        return(false);
    }