Как проверить коллизии с SFML (при использовании сущности базового класса) - PullRequest
0 голосов
/ 30 мая 2020
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);
};

1 Ответ

0 голосов
/ 31 мая 2020

Вы можете выполнить простое наследование от класса Entity. Я не знаю, почему ваша программа вылетает при возврате sf::FloatRect объектов. Это также должно быть правильным решением этой проблемы.

#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);
}
...