I'm working on a project for school and I'm having some trouble solving a bug. When the player collides with a rectangle the sprite/hitbox keeps jittering while the player has momentum in the direction.
I'm guessing that the reaction sometimes moves it so that they are right next to each other and sometimes it makes it so that there is a 1 pixel space between. Is this because I'm using float and it sometimes rounds up? If so what is a good way to solve it?
The order it happens in gameloop is:
Update player position
Check collision (move if there is one)
draw player to window
The code I use for collision detection and reaction is:
void Collider::collisionTest(Player &player, sf::RectangleShape &rec2, float push) {
float intersectX;
float intersectY;
float deltaX;
float deltaY;
if(AABBCollision(player.getHitbox(),rec2, intersectX, intersectY, deltaX, deltaY))
{
push = std::min(std::max(push,0.0f), 1.0f);
if(intersectX > intersectY){
if (deltaX > 0.0f){
player.playerMoveCollision(intersectX * (1.0f - push), 0.0f);
rec2.move(-intersectX * push, 0.0f);
}else
{
player.playerMoveCollision(-intersectX * (1.0f - push), 0.0f);
rec2.move(intersectX * push, 0.0f);
}
}else{
if (deltaY > 0.0f){
player.playerMoveCollision(0.0f,intersectY * (1.0f - push));
rec2.move(-intersectY * push, 0.0f);
player.setIsJumping(false);
}else
{
player.playerMoveCollision(0.0f,-intersectY * (1.0f - push));
rec2.move(0.0f, intersectY * push);
}
}
};
}
bool Collider::AABBCollision(sf::RectangleShape& rec1, sf::RectangleShape& rec2, float& intersectX,float& intersectY,float& deltaX,float& deltaY) {
sf::Vector2f rec1Position = rec1.getPosition();
sf::Vector2f rec1HalfSize = rec1.getSize() * 0.5f;
sf::Vector2f rec2Position = rec2.getPosition();
sf::Vector2f rec2HalfSize = rec2.getSize() * 0.5f;
deltaX = rec2Position.x - rec1Position.x;
deltaY = rec2Position.y - rec1Position.y;
intersectX = abs(deltaX) - (rec2HalfSize.x + rec1HalfSize.x);
intersectY = abs(deltaY) - (rec2HalfSize.y + rec1HalfSize.y);
if (intersectX < 0.0f && intersectY < 0.0f){
return true;
}
return false;
}
Edit:
So i kinda solved it in whats probably a bad way.
The problem was using abs(deltaX/deltaY) as i shaved off the decimal point of the float.
What i did to solve it was:
intersectX = abs(deltaX) - (rec2HalfSize.x + rec1HalfSize.x);
intersectY = abs(deltaY) - (rec2HalfSize.y + rec1HalfSize.y);
into
if(deltaX < 0)
{
intersectX = (deltaX * -1) - (rec2HalfSize.x + rec1HalfSize.x);
}else
{
intersectX = deltaX - (rec2HalfSize.x + rec1HalfSize.x);
}
if(deltaY < 0)
{
intersectY = (deltaY * -1) - (rec2HalfSize.y + rec1HalfSize.y);
}else
{
intersectY = deltaY - (rec2HalfSize.y + rec1HalfSize.y);
}