SFML community forums

Help => General => Topic started by: R_oot42O on February 06, 2022, 03:40:32 pm

Title: Rectangle bottom collision issues
Post by: R_oot42O on February 06, 2022, 03:40:32 pm
Hello everyone, I have a problem with bottom collision detection in my project.


I have a function that checks if the bottom of the character collides with a platform, it almost work as wanted, but there is a problem, actually it works only with some platforms but will fail with others.

See the screens below.


Working : (https://i.ibb.co/8YvzhBY/Ok.png) (https://ibb.co/DrcGqbr)


Not working :(https://i.ibb.co/7C5G43n/not-ok.png) (https://ibb.co/H4srdct)


On the first screenshot, we can see the collisions fits perfectly, but in the second screen the character is overlapping the platform.


Here's the code for bottom collision detection :

bool Character::isBottomColliding(Platform *platforms)
{
   int i;
   sf::FloatRect characterRect;
   sf::FloatRect platformRect;
   characterRect = getRect();
   for(i = 0; i < LEVEL_MAX_PLATFORMS; i++)
   {
      platformRect = platforms[i].getRect();
      if(characterRect.left + characterRect.width >= platformRect.left && characterRect.left <= platformRect.left + platformRect.width && characterRect.top + characterRect.height >= platformRect.top)
      {
         isGrounded = true;
         isJumping = false;
         return true;
      }  
   }
   return false;  
}

The update function :


void update(Level *level, Character *character)
{
   if(character->falling() && !character->isBottomColliding(level->getPlatforms()))
   {
      character->fall(); //This function is moving character down to simulate gravity
   }
   character->move();
}


I don't understand why it works with the first platforms but not with the other one.


Sorry if my english was bad, this is not my native language.


EDIT : It works fine when gravity is set to 1


void Character::fall()
{
   sprite.setPosition(getRect().left, getRect().top + gravity);
   isFalling = true;
   isGrounded = false;  
}

EDIT 2: I found that when the platform's Y position modulus (%) the gravity equals 0, there is no problem

if platformRect.top % gravity == 0 ==> No collision problems







 
Title: Re: Rectangle bottom collision issues
Post by: fallahn on February 06, 2022, 04:48:33 pm
Detecting the collision and stopping falling is not enough on its own. You also have to calculate how much overlap (aka penetration) the collision created and move the character back by that much, so that it lines up with the platform. I wrote a post about simple collision detection some time back, it may be useful here.

https://trederia.blogspot.com/2016/02/2d-physics-101-pong.html
Title: Re: Rectangle bottom collision issues
Post by: R_oot42O on February 06, 2022, 05:25:01 pm
Thank you for your reply, i'll check it out.