老卢写的 判断点在六边形内


--检测一个点是否在一个6边形了内
function g_isContain(touchPos,itemPos,nRad)
    
    local function isLine(point1,point2,z)
        local number1 = point2.x - point1.x;
        local number2 = z.y - point1.y;
        local number3 = point2.y - point1.y;
        local number4 = z.x - point1.x;
        local number5 = number1 * number2 - number3 * number4;
        return number5;
    end

    local function isMeetLine(point1,point2,point,z)
        local bRet = false;
        if (point1.x == point2.x) and (point1.y ~= point2.y) then
            if (z.x >point1.x and point.x > point1.x) or
            (z.x < point1.x and point.x < point1.x) or (z.x == point1.x) then
                bRet = true;
            end
            return bRet;
        end
        if (point1.y == point2.y and point1.x ~= point2.x) then
            if ((z.y > point1.y and point.y > point1.y) or
            (z.y < point1.y and point.y < point1.y) or z.y == point1.y) then
                bRet = true;
            end
            return bRet;
        end
        if ((isLine(point1,point2,z) >= 0 and isLine(point1,point2,point) >= 0) or
        (isLine(point1,point2,z) < 0 and isLine(point1,point2,point) < 0)) then
            bRet = true;
        else
            bRet = false;
        end
        return bRet;
    end

    local points = {}
    local pts = {}
    local rad = nRad or 40
    local sx = itemPos.x
    local sy = itemPos.y
    local sAngle = 30
    for i=1,6 do
        sAngle = sAngle%360
        local ag = sAngle/180*math.pi
        local x = sx+rad * math.sin(ag)
        local y = sy+rad * math.cos(ag)
        local ps = {}
        ps.x = x
        ps.y = y
        table.insert(points,ps)
        table.insert(pts,{x,y})
        sAngle = sAngle + 60
    end

    local vecPoint = points
    local point = touchPos

    local bRet = true;
    local size = #vecPoint
    for i=1,size do
        if i == size then
            if not isMeetLine(vecPoint[i],vecPoint[1],point,vecPoint[2]) then
                bRet = false
                break
            end
        elseif i == size - 1 then
            if not isMeetLine(vecPoint[i],vecPoint[i+1],point,vecPoint[1]) then
                bRet = false
                break
            end
        else
            if not isMeetLine(vecPoint[i],vecPoint[i+1],point,vecPoint[i+2]) then
                bRet = false
                break
            end
        end
    end
    return bRet
end

--检测是否点击在一个6边形内
function g_isCheckItem(sender,nRad)
    local touchPos = sender:getTouchBeganPosition()
    local itemPos = sender:getParent():convertToWorldSpace(cc.p(sender:getPosition()))
    return g_isContain(touchPos,itemPos,nRad)
end

你可能感兴趣的:(老卢写的 判断点在六边形内)