Search code examples
c++sfmlgame-development

How to check for collisions with SFML (While using a Base class Entity)


class Entity
{
private:
    //Functions
    void initiVariables();


protected:
    //Variables
    float velocity;
    sf::Sprite  sprite;
    sf::Texture* texture;

    MovementComponent* movementComponent;
    AnimationComponent* animationComponent;
    HitboxComponent* hitboxComponent;

    //Component Functions
    void setTexture(sf::Texture& texture);
    void **strong text**MovementComponent(float maxVelocity, float acceleration, float deacceleration);
    void AnimationComponent(sf::Sprite& sprite, sf::Texture& texture);
    void HitboxComponent(sf::Sprite& sprite, sf::Color wireColor, float wireThickness);

public:
    //Constructor & Deconstructor
    Entity();
    virtual~Entity();

    //Accessor
    const sf::FloatRect& getGlobalBounds() const; 

//when I check for Collsion sprite.getGlobalBounds().intersect(sprite.getGlobalBounds()) 
//it remains true for the entire time what am doing wrong?

    //Funtions
    void setPosition(const float x, const float y);
    virtual void move(const float x, const float y, const float& dt);
    virtual void update(const float& dt);
    virtual void render(sf::RenderTarget* target);
};

Solution

  • You can do simple inheritance from the Entity class. I don't know why your program crashes when returning sf::FloatRect objects. This should also be the correct solution to this problem.

    #include <SFML/Graphics.hpp>
    #include <iostream>
    
    class Entity : public sf::RectangleShape { 
    public:
        bool isColliding(Entity const& other) {
            return this->getGlobalBounds().intersects(other.getGlobalBounds());
        }
    };
    
    class Player : public Entity {};
    class Zombie : public Entity {};
    
    int main() {
        Player player;
        player.setPosition({ 200, 200 });
        player.setSize({ 100, 100 });
    
        Zombie enemy;
        enemy.setPosition({ 151, 151 });
        enemy.setSize({ 50, 50 });
    
        std::cout << player.isColliding(enemy);
    }