Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: If function for collision not working together  (Read 1351 times)

0 Members and 1 Guest are viewing this topic.

Jan666

  • Jr. Member
  • **
  • Posts: 64
    • View Profile
If function for collision not working together
« 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);
   
}
 

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11034
    • View Profile
    • development blog
    • Email
Re: If function for collision not working together
« Reply #1 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.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

 

anything