I need some help working out the class hierarchy for a game I'm developing with JavaScript. The game is a top-down space shooter with (at its basic level) a background, player, bullets and enemies.
I've come up with a class diagram which I think needs to be improved on:
Nothing out of the ordinary here, the main class is called Cosmos (the name of the game) which has a tick()
method which fires at roughly 60 times per second. The Background
, Player
and Enemy
classes belong to Cosmos
and the Bullet
class belongs to the Player
class, because a Player
"owns" Bullet
s.
There is one major problem that comes to mind with this diagram though, and that is how I'll do collision detection between the players bullets and the enemies. I could write a method in the Player
class to pass a bullet's x
and y
to Cosmos
and do the collision detection in Cosmos
, but that doesn't seem like the best way to do it. Would doing the collision detection in Cosmos
be okay if I'm going for a neat, organisable approach?
Any other modifications you could make to make my life easier is also greatly appreciated.
Your diagram seems to have some issues. You wrote:
The Background, Player and Enemy classes belong to Cosmos and the Bullet class belongs to the Player class, because a Player "owns" Bullets."
This suggests an aggregate or composite relationship, but in your diagram you use inheritance arrows... You have Player
extending Bullets
, and multiple inheritance on Cosmos
, which extends Player
, Background
, and Enemy
. Also, your diagram is upside down; generally base classes go at the top.
If you want to use inheritance chains, consider something like this instead: