A little lost on how a program/classes should be structured.


I'm making a small game with SFML just as a learning project. I'm doing decent so far but one thing I feel like I'm not doing "properly" is where I'm putting certain functions and how things should be called.

For example, I have a Game class, Player class, and Bullet class. Game has a vector of Player objects and Players has a vector that holds the bullet objects that player has fired.

If I draw the bullet objects in the main class, is the only way to get the bullet objects to the main class to call game.getPlayers.at(p).getBulletsFired.at(b).getBullet(); ?
It seems like a convoluted way to do it which is why I feel like I'm doing something wrong. I know I could make a function in Game which could get a player which could call a function to get the individual bullet, but that doesn't seem right either. What am I missing?
Make the Game responsible for the bullets.

Sure, the player is responsible for instantiating a bullet instance (player.gun.fire()), but after that, the bullet is it's own self-contained instance with it's own trajectory through the Game space.

Or maybe the bullets already exist in the game, say as a vector of bullets in an ammo clip that the player finds around the Game.

Firing a bullet is just really giving it a particularly high velocity in a particular direction, then letting the game engine do it's thing with just another object that happens to be moving in the scene.

When the bullet is in the player's clip or gun, the clip or gun owns it.

But when the bullet is fired, it's no longer owned by the player, it's owned by the game as salem says. So at that point, remove it from the player's gun and put in the collection of fired bullets in the game.

More generally, use the [] operator instead of at():
game.getPlayers[p].getBulletsFired[b].getBullet();

But sometimes the data is unavoidably complex. In those cases, create a temporary reference to whatever you need. So if game.getPlayers[p].getBulletsFired is a vector of Bullet then:

1
2
vector<Bullet> &bullets(game.getPlayers[p].getBulletsFired);  // shorthand for player's bullets
// Now use bullets. 

An important point here is that this technique has no performance penalty.
Topic archived. No new replies allowed.