
-----------------------------------
Mr. T
Thu Jul 19, 2007 7:19 pm

2d Tile Based Gaming -- Collision Detection Help
-----------------------------------
I decided to remake my BreakOut game using the new knowledge I had gained from CodeMonkey's 2d Tile tutorial. My collision detecton is a bit off. Help would be appreciated.

-----------------------------------
CodeMonkey2000
Thu Jul 19, 2007 11:06 pm

Re: 2d Tile Based Gaming -- Collision Detection Help
-----------------------------------
The method I showed works best with top-down games. there is a more flexible method for collision. Basically imagine that the ball is enclosed in an imaginary box. You need to know the midpoint of the box/circle and the distance from the mid-point to the sides of the box. Using this, check where what tiles the corners of the box will be in if the ball continues to move. If any of the corners are not in tile 0, then a collision has occurred.
http://img389.imageshack.us/img389/9372/untitledjm6.png

Here's a function that you may find useful. Just pass in where the ball will be, and its radius. 

fcn collide (x, y, r : int) : boolean
    % coner#1
    if tiles ((x - r) div 20, (y + r) div 20) not= 0 then
        result true
        %corner #2
    elsif tiles ((x + r) div 20, (y + r) div 20) not= 0 then
        result true
        %corner#3
    elsif tiles ((x - r) div 20, (y - r) div 20) not= 0 then
        result true
        %corner#4
    elsif tiles ((x + r) div 20, (y - r) div 20) not= 0 then
        result true
    end if
    result false
end collide


-----------------------------------
Mr. T
Thu Jul 19, 2007 11:32 pm

Re: 2d Tile Based Gaming -- Collision Detection Help
-----------------------------------
I implemented the function, but the ball nonetheless gets caught when it hits the corner of a brick.

-----------------------------------
CodeMonkey2000
Fri Jul 20, 2007 3:04 pm

Re: 2d Tile Based Gaming -- Collision Detection Help
-----------------------------------
That's because you aren't checking for a diagonal collision. Try this code, it isn't efficient but you should be able to simplify it. Also remember that the maximum size of the radius should be 10. If it's bigger you'll need to break the circle down to smaller squares. 

if collideX (x (i) + dx (i), y (i) + dy (i), RADIUS) and not collideX (x (i) + dx (i), y (i), RADIUS) and not collideY (x (i), y (i) + dy (i), RADIUS) then
            dx (i) := -dx (i)
            dy (i) := -dy (i)
        else
            if collideX (x (i) + dx (i), y (i), RADIUS) then
                dx (i) := -dx (i)
            end if
            if collideY (x (i), y (i) + dy (i), RADIUS) then
                dy (i) := -dy (i)
            end if
        end if

