2d游戏中的射线与矩形检测碰撞

 cc.exports.LineCollideRect(startLine,endLine,rect)--向量与矩形检测碰撞

  --获取矩形的四个顶点位置

    local p = {cc.p(rect.x,rect.y),cc.p(rect.x + rect.width,rect.y),cc.p(rect.x+rect.width,rect.y + rect.height),cc.p(rect.x,rect.y+rect.height)}

    local bRight = PointPosInVector(startLine,endLine,p[1])--记录矩形的第一个点在射线的左边还是右边

    for i = 2,4 do--遍历其他三个点

        if bRight ~= PointPosInVector(startLine,endLine,p[i]) then--如果其他顶点跟第一个顶点的左右边不相同,则说明射线与矩形碰撞到

            return true

        end

    end

    return false

end

 

function cc.exports.PointPosInVector(startPos,endPos,v)--判断点在向量的左右侧,true为左侧,false为右侧,startPos是向量的起点,endPos是向量的终点,v是顶点

    if (startPos.x - v.x)*(endPos.y - v.y) - (startPos.y - v.y) * (endPos.x - v.x) > 0 then

        return true

    end

    return false

end

 

posted on 2015-09-17 17:27  HemJohn  阅读(704)  评论(0编辑  收藏  举报

导航