SFML community forums

Help => Graphics => Topic started by: Jan666 on July 18, 2022, 12:33:45 pm

Title: Collision dont work exactly
Post by: Jan666 on July 18, 2022, 12:33:45 pm
Hello,
I have a collision question, the following code works, but when the player come the wall closer, the wall attracts the player like a magnet, can someone tell me how to fix it?

for (auto& wall : walls){
       
        FloatRect wallBounds = wall.getGlobalBounds();
        FloatRect playerBounds = player.getGlobalBounds();
       
nextPos = playerBounds;
nextPos.left += Vec.x ;
nextPos.top += Vec.y;
       
        if(wallBounds.intersects(nextPos)){
                       
        //Bottom Collision
 if (Vec.y > 0 && playerBounds.left < wallBounds.left + wallBounds.width && playerBounds.left + playerBounds.width > wallBounds.left )
         {
        Vec.y = 0;
          player.setPosition(playerBounds.left, wallBounds.top - playerBounds.height);
          }
        //Top Collision
if(Vec.y < 0 && playerBounds.left < wallBounds.left + wallBounds.width && playerBounds.left + playerBounds.width > wallBounds.left)
          {
                Vec.y = 0;
                player.setPosition(playerBounds.left, wallBounds.top + wallBounds.height);
            }  
 //Right Collision
if(Vec.x > 0 && playerBounds.top < wallBounds.top + wallBounds.height && playerBounds.top + playerBounds.height > wallBounds.top)
                   {
                  Vec.x = 0;
                 player.setPosition(wallBounds.left - playerBounds.width, playerBounds.top);
                   }
//Left Collision
if (Vec.x < 0 && playerBounds.top < wallBounds.top + wallBounds.height && playerBounds.top + playerBounds.height > wallBounds.top)
                      {
                      Vec.x = 0;
player.setPosition(wallBounds.left + wallBounds.width , playerBounds.top);

                      }
           
      }
 
Title: Re: Collision dont work exactly
Post by: eXpl0it3r on July 21, 2022, 11:18:55 am
Would require some more mental effort to fully understand your code.

The usual issue in such a case is, that you're not correctly reacting to the collision.
Once two object overlap, i.e. collide, then you need to correctly handle the moving of the two objects into a state where they aren't overlapping anymore. If you don't do that in the right way, the objects end up permanently "glued" together.
Also if you do that check too early, it can feel like whenever you get close that they "attract" each other, so make sure you're not doing the check when they aren't yet colliding.
Title: Re: Collision dont work exactly
Post by: fallahn on July 21, 2022, 11:23:17 am
If it helps I wrote a post some time back which covers basic collision detection with SFML: https://trederia.blogspot.com/2016/02/2d-physics-101-pong.html