I have an Entity baseclass which the classes Player and Enemy Inherit.
class Entity
{
public:
virtual void Update(sf::RenderWindow &window) {};
virtual void Draw(sf::RenderWindow &window) {};
};
Both player and enemy contain a sprite object that looks like this:
class Player : Entity
{
public:
sf::Sprite sprite
void Update(sf::RenderWindow &window);
void Draw(sf::RenderWindow &window)
}
Player and Enemy are created inside a vector which is set up like this:
class EntityManager
{
public:
void CollisionCheck();
private:
std::vector<Entity*> entityVector;
}
I'm looking to use a collision detection function of this form:
bool Collision::CircleTest(const sf::Sprite& Object1, const sf::Sprite& Object2)
So I'm trying to do something like this:
void EntityManager::ColCheck()
{
if (Collision::CircleTest(entityVector[0]->sprite, entityVector[1]->sprite))
{
cout << "COLLISION\n";
}
}
This results in the following compile error:
‘class Entity’ has no member named ‘sprite’
I'm unsure how to create a dummy sprite in Entity so that I can access the player and enemy sprites using the above method. Is this possible?
I'm stumpe开发者_开发知识库d and would greatly appreciate any help anyone can offer!
If everything in your code that derives from Entity
has a sprite
object, then you should declare that object in the base class.
Not declaring the object in the base class means that there could be a class inheriting from Entity
that does not have a sprite object, which means that ColCheck
has no valid basis for assuming that elements of entityVector
point to something that has a variable called sprite
. Make sense?
You probably shouldn't create a dummy unless having a sprite is something ALL entities have.
What you might want is to use a visitor pattern or possibly one of the many multiple-dispatch implementations. Which and what will end up having to be up to you.
If both Player
and Enemy
classes contain sprite
, why not declare it inside Entity
? This should solve your problem.
You could make a member function sprite()
that is declared as a pure virtual function inside Entity
:
class Entity {
public:
virtual void Update(sf::RenderWindow &window) {};
virtual void Draw(sf::RenderWindow &window) {};
virtual sf::Sprite& sprite() = 0;
};
Then, the Player
and Enemy
implementations would return the sf::Sprite
instance variables each has. However, the other posters bring up a valid point; it might make sense to have the sprite be in the base class if all derived classes are going to have one.
精彩评论