SFML community forums

Help => Graphics => Topic started by: Jan666 on August 15, 2022, 10:23:08 am

Title: If function for collision not working together
Post by: Jan666 on August 15, 2022, 10:23:08 am
Can someone Tell me why these four if functions not working together and how to fix it?

(playerBounds.intersects(wallBounds)){

if(wallBounds.left < playerBounds.left + playerBounds.width )

player.setPosition(wallBounds.left + wallBounds.width, playerBounds.top);


 if(playerBounds.left < wallBounds.left)

  player.setPosition(wallBounds.left - playerBounds.width, playerBounds.top);

if(wallBounds.top < playerBounds.top + playerBounds.height )

player.setPosition(playerBounds.left,  wallBounds.top + wallBounds.height);


 if(playerBounds.top < wallBounds.top)

  player.setPosition(playerBounds.left  , wallBounds.top - playerBounds.height);
   
}
 
Title: Re: If function for collision not working together
Post by: eXpl0it3r on August 15, 2022, 05:34:04 pm
I really recommend you use a debugger or print out some values to see what's going on with your calculations, plus write down the expected scenarios on paper, at least that's what I usually do in such situations.

if(wallBounds.left < playerBounds.left + playerBounds.width )
    player.setPosition(wallBounds.left + wallBounds.width, playerBounds.top);
Translated to English this would read as:
If the walls left side is smaller than the players right side, then set the player walls right side.

Or said differently:
If the players right side is in the walls left side, then move the player to the right side of the wall.

Which means the player would "teleport" through the wall, when hitting it from the left side.
I don't think that's the behavior you're going for.

I'd recommend to keep the player and wall checks always in the same order in the if expressions (if player x wall), that prevents some issues, when you try to go through the different statements.