Circle-Rectangle collision in a tile map game
- by furiousd
I am making a 2D tile map based putt-putt game.
I have collision detection working between the ball and the walls of the map, although when the ball collides at the meeting point between 2 tiles I offset it by 0.5 so that it doesn't get stuck in the wall. This aint a huge issue though.
if(y % 20 == 0) {
y+=0.5;
}
if(x % 20 == 0) {
x+=0.5;
}
Collisions work as follows
Find the closest point between each tile and the center of the ball
If distance(ball_x, ball_y, close_x, close_y) <= ball_radius and the closest point belongs to a solid object, collision has occured
Invert X/Y speed according to side of object collided with
The next thing I tried to do was implement floating blocks in the middle of the map for the ball to bounce off of. When a ball collides with a corner of the block, it gets stuck in it. So I changed my determineRebound() function to treat corners as if they were circles. Here's that functon:
`i and j are indexes of the solid object in the 2d map array. x & y are centre point of ball.`
void determineRebound(int _i, int _j) {
if(y > _i*tile_w && y < _i*tile_w + tile_w) {
//Not a corner
xs*=-1;
} else if(x > _j*tile_w && x < _j*tile_w + tile_w) {
//Not a corner
ys*=-1;
} else {
//Corner
float nx = x - close_x;
float ny = y - close_y;
float len = sqrt(nx * nx + ny * ny);
nx /= len;
ny /= len;
float projection = xs * nx + ys * ny;
xs -= 2 * projection * nx;
ys -= 2 * projection * ny;
}
}
This is where things have gotten messy. Collisions with 'floating' corners work fine, but now when the ball collides near the meeting point of 2 tiles, it detects a corner collision and does not rebound as expected.
I'm a bit in over my head at this point. I guess I'm wondering if I'm going about making this sort of game in the right way. Is a 2d tile map the way to go? If so, is there a problem with my collision logic and where am I going wrong?
Any advice/feedback would be great.