Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat
Simple BoxNormalCollision function - Gideros Forum

Simple BoxNormalCollision function

Maybe someone find it useful, I used it in my game that I never finished ..

function BoxNormalCollision(ObjA,ObjB)
    local x, y = 0,0 
    local a = {x= ObjA:getX(), y= ObjA:getY(), w= ObjA:getWidth(), h= ObjA:getHeight()}
    local b = {x= ObjB:getX(), y= ObjB:getY(), w= ObjB:getWidth(), h= ObjB:getHeight()}
 
    if -- first test for any collision
    (
        a.x < b.x+b.w and
        b.x < a.x+a.w and
        a.y < b.y+b.h and
        b.y < a.y+a.h
    ) 
    then -- test from where does collision come
        local ax0 = a.x + a.w /2
        local ay0 = a.y + a.h /2
        local bx0 = b.x + b.w /2
        local by0 = b.y + b.h /2
        --desno dolje
        if bx0 > ax0 and by0 > ay0 then
            if (a.x+a.w) - b.x > (a.y+a.h) - b.y then
                y = -1
                ObjA:setY(b.y-a.h)
            else
                x = -1
                ObjA:setX(b.x-a.w)
            end		
            return x,y
        --desno gore
        elseif bx0 > ax0 and by0 < ay0 then
            if (a.x+a.w) - b.x > (b.y+b.h) - a.y then
                y = 1
                ObjA:setY(b.y+b.h)
            else
                x = -1
                ObjA:setX(b.x-a.w)
            end		
            return x,y
        --lijevo dolje
        elseif bx0 < ax0 and by0 > ay0 then
            if (b.x+b.w) - a.x > (a.y+a.h) - b.y then
                y = -1
                ObjA:setY(b.y-a.h)
            else
                x = 1
                ObjA:setX(b.x+b.w)
            end
            return x,y
        --lijevo gore
        elseif bx0 < ax0 and by0 < ay0 then
            if (b.x+b.w ) - a.x > (b.y+b.h) - a.y then
                y = 1
                ObjA:setY(b.y+b.h)
            else
                x = 1
                ObjA:setX(b.x+b.w)
            end
            return x,y
        --
        end  
    end
    return x,y
end



-demo proj is attached

Likes: Apollo14

zip
zip
ncol_demo.zip
3K
+1 -1 (+1 / -0 ) Share on Facebook

Comments

Sign In or Register to comment.