Collision Testing
Posted: Mon Jun 28, 2010 2:23 pm
I'm having some problems with collision detection. I used the one I found on this forum, and it seems to pretty much work, although I didn't really understand how it works... Here is some code:
The problem is that when a collision is detected... the player keeps going up and down like mad when it's a y axis collision and keeps going left-right when it's a x axis collision... I've been trying to fix that for a couple of days, and I got no idea how...
Here some more pieces of code that might help:
Any idea on where I failed? Also just to mention I didn't understand the algorithm ... maybe someone could spare some time to explain ?
P.S. rect1 belongs to the player, and rect2 belongs to the other entity
Code: Select all
//// INSIDE Player::handle_collision()
// ... //
//Determine overlap for each axis
int xDist = abs((rect1.x + rect1.w / 2) - (rect2.x + rect2.w / 2));
int yDist = abs((rect1.y + rect2.h / 2) - (rect2.y + rect2.h / 2));
Singleton<Log>::getInstance()->print("Rect2: x(%d), y(%d)", rect2.x, rect2.y);
//minimal amount of distance that the two can be apart and not collide
int xMinDist = rect1.w/2 + rect2.w;
int yMinDist = rect1.h/2 + rect2.h;
//neither axis is colliding
if(xDist >= xMinDist || yDist >= yMinDist) {
continue;
}
int xOverlap = xDist - xMinDist;
int yOverlap = yDist - yMinDist;
collidedTimes++;
onObject = false;
if(abs(xOverlap) < abs(yOverlap)) {
//move the player by the amount of the overlap
if(rect2.x < rect1.x) {
x += std::abs(xOverlap);
} else {
x -= std::abs(xOverlap);
}
} else {
if(rect2.y < rect1.y){
y += std::abs(yOverlap);
onObject = true;
}
else {
y -= std::abs(yOverlap);
}
}
}
}
Here some more pieces of code that might help:
Code: Select all
void Player::update()
{
//only add gravity if he's not on objects.. this is pretty dumb.. must modify it
if(!onObject) Singleton<Physics>::getInstance()->apply_gravity(this);
update_collision(); //move the collision box to match players coords
handle_collision(); //handles the collision
move(); //moves players coords based on the velocities
handle_input(); //handle input and updates velocities
draw(); //renders the player sprite on screen
}
P.S. rect1 belongs to the player, and rect2 belongs to the other entity