Search code examples
c++collisionsfml

The collision in SFML is not that good, how to improve it?


I've been lately working on a simple game using C++ and SFML latest version, but I had a problem which is that the collision detection is not that good, for example the player dies even if the enemy didn't touch him yet, but just near him. Here is the code of the player class with the move function and collision detection code AND the moves of the enemy class:

`class PlayerA : public CircleShape { public:

    //Constructor:
    PlayerA(float xposition, float yposition, float radius, float s)
    {
        setRadius(radius);
        setFillColor(Color::Yellow);
        setOutlineColor(Color(00,80,00));
        setOutlineThickness(-2);
        setPointCount(3);
        setSpeed(s);
        setPosition(xposition,yposition);
    }

    //Movements of the player:
    void up()
    {
        move(0,-10*speed);
    }
    void down()
    {
        move(0,10*speed);
    }
    void right()
    {
        move(10*speed,0);
    }
    void left()
    {
        move(-10*speed,0);
    }
     void checkA(ObsA *obs1=NULL,ObsA *obs2=NULL, ObsA *obs3=NULL, ObsA *obs4=NULL, ObsA *obs5=NULL)
    {
        if(obs2==NULL)
        {
            if(getGlobalBounds().intersects(obs1->getGlobalBounds()))
            {
                relevel();
            }
        }
     private:
      float speed=0.00;

    void obs()
    {
        if(speed > 0)
        {
                rotate(0.5*speed);
        }
        else
        {
                rotate(0.5*speed);
        }
    }


private:
    float speed = 0.00;


    void obs()
    {
        if(speed > 0)
        {
                rotate(0.5*speed);
        }
        else
        {
                rotate(0.5*speed);
        }
    }


private:
    float speed = 0.00;

Is there something wrong with the code, how to fix the problem, thank you!


Solution

  • The intersects function just check if two rectangles intersect. If you want pixel perfect collision detection in SFML you have to write that yourself.

    Basically, start with intersects, if it is true, then get the intersecting rectangle and check if any pixels therein from both original rectangles contains overlaping relevant pixels.