Freesnöw
Freesnöw

Reputation: 32133

2D Collision problems

I have the following code:

function collisionDetect(left1,right1,top1,bottom1,left2,right2,top2,bottom2,dir)
    local left,right,top,bottom=false,false,false,false
    if left1<right2 then left=true end
    if right1>left2 then right=true end
    if top1>bottom2 then top=true end
    if bottom1<top2 then bottom=true end
    if dir.x>0 and (top or bottom) then
        if right then return 1 end
    elseif dir.x<0 and (top or bottom) then
        if left then return 2 end
    elseif dir.y>0 and (left or right) then
        if bottom then return 3 end
    elseif dir.y<0 and (left or right) then
        if top then return 4 end
    end
    return 0
end

left1, right1, etc. are arguments containing the position of the respective bounding box (box 1 or 2).

dir is a "Vector2" (contains an x and y property).

For some reason, my code is returning collisions for objects no where near by. Any ideas?

EDIT:

I have solved my problem, here is the code for anybody googling the subject.

(It's in Lua, a pretty straight forward and simple to interpret language)

function collisionDetect(left1,right1,top1,bottom1,left2,right2,top2,bottom2,dir)
    local insideHorizontal=false
    local insideVertical=false
    if left1<right2 then insideHorizontal=true end
    if right1>left2 then insideHorizontal=true end
    if top1>bottom2 then insideVertical=true end
    if bottom1<top2 then insideVertical=true end
    if insideHorizontal and insideVertical then
        return true
    end
    return false
end

Upvotes: 1

Views: 258

Answers (1)

Skilldrick
Skilldrick

Reputation: 70819

Have a look at this for a nice collision detection tutorial/algorithm.

Essentially:

bool check_collision( SDL_Rect A, SDL_Rect B )
{
   //...
   //Work out sides
   //...

   //If any of the sides from A are outside of B
    if( bottomA <= topB )
    {
        return false;
    }

    if( topA >= bottomB )
    {
        return false;
    }

    if( rightA <= leftB )
    {
        return false;
    }

    if( leftA >= rightB )
    {
        return false;
    }

    //If none of the sides from A are outside B
    return true;
}

Or, in terms of your code:

function collisionDetect(left1,right1,top1,bottom1,left2,right2,top2,bottom2,dir)
    if bottom1<=top2 then return true end
    if top1>=bottom2 then return true end
    if right1<=left2 then return true end
    if left1<=right2 then return true end
    return false
end

(this isn't a language I know, so I'm guessing a bit)

Upvotes: 2

Related Questions