Implementing collision check for classes derived from same base class

Viewed 56

I have a base class MovingObject defined like this:

class MovingObject
{
protected:
    double x;
    double y;
    double speed;
    double damage;
    double distance(double x1, double y1, double x2, double y2)
    {
        return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
    }
public:
    MovingObject(double x, double y, double speed, double damage);
    virtual bool isCollide(MovingObject* Object);
    virtual void draw() {};
    virtual void move() {};
};

And I have 2 inherited classes from MovingObject class, Zombie and Bullet :

class Bullet : public MovingObject
{
private:
    double dirX;
    double dirY;
public:
    Bullet(double x, double y, double speed, double damage, double dirX, double dirY);
    bool isCollide(Zombie* pZombie);
    void draw();
    void move();
};
class Zombie : public MovingObject
{
private:
    double hpMax;
    double hpCurrent;
    double attackCD;
    double attackRate;
public:
    Zombie(double x, double y, double speed, double damage, double hpMax, double hpCurrent, double attackCD, double attackRate);
    bool isCollide(Bullet* pBullet);
    void draw();
    void move();
    void getHit();
    void drawHPBar();
    void decreaseAttackCD();
    void refreshAttackCD();
};

For example, lets say I want to check collision between Bullet and Zombie objects in the game. I want to check this collision in Bullet class like follows:

bool Bullet::isCollide(Zombie* pZombie) {
    if (distance(x, y, pZombie->x, pZombie->y) < 10) {
        pZombie->getHit();
        return true;
    }
    else
        return false;
}

But when I try to access the x and y attributes of Zombie in Bullet class, I can't access it. What I want to ask is, is it possible to check collision like this without using getX() and getY() functions ? I believe there is a flaw in my thinking because I am fairly new to C++ and OOP concepts. I do not want to full answer from you, I just want someone to point right path for me. Thank you in advanced.

1 Answers

Bullet cannot access Zobmbies protected members because it is not derived from Zombie. If you only need read access to x and y, you need constant getters in the MovingObject class.

class MovingObject
{
public:
  double GetX() const { return x; }
  double GetY() const { return y; }
protected:
...
};

and then use them in Bullet::isCollide()

if (distance(x, y, pZombie->GetX(), pZombie->GetY()) < 10) {
  pZombie->getHit();
  return true;
}

Please avoid using friend. With growing number of subclasses you will have to make them all friends.

Related