开发者

Share variables between classes C++?

Yet another question about classes as Im new to OOP. I am creating a game just for fun. Its a top down shooter, space shooter.

I have a few different classes:

Bullet (a list of bullet coordinates), Player (player sprite, position etc), Enemy (enemy sprite, position etc), Collision (taking coordinates Ax, Ay, and Bx, By to see if they have collided)

How can I send the coordinates from Bullet, Enemy t开发者_开发技巧o the Collision class to see if they have collided?

Collision col
col.collision(ax, ay, bx, by) //how can I get the Player and Bullet pos?


Probably what you want to do is to have a common class "SceneObject" that has a position. Then Player, Enemy and Bullet all inherit from that class.

Your Collision then does not need knowledge about Players, Enemies etc. but only SceneObjects which have a position. You can write a Getter method in your base class that returns the position.


I would create a base class for Bullet, Enemy (and maybe Player). Let's call it Object and the Object would own the Coordinates and would have a function determining if a Collision happened.

In code it would look like to following:

class Object 
{
    private:
        Coord position; 

    public:
        bool Collide(const Object& otherObject) const;
};


You typically have to go through every enemy and check the coordinates of that enemy against your player coordinates.
I'm sure you stored those enemies somewhere, preferably in a container like std::vector. Now let me just assume you did exactly that:

// somewhere in a 'Game' class
std::vector<Enemy> myEnemies;
Player myPlayer;
Collision col;

for(int i=0; i < myEnemies.size(); ++i){
  col.collision(myPlayer.getX(), myPlayer.getY(), myEnemies[i].getX(), myEnemies[i].getY())
}

And that's it. :) You do the same for bullets and similar objects. Save them all in a container, iterate over that container, and check the positions of the objects.
Now, for another tip, if a class only contains methods and no variables, you may aswell make that free functions. Just because you use OOP in some parts of your project doesn't require you to use it everywhere. Make that collision a free function and be done with it. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜