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