1
\$\begingroup\$

Say you have missiles or rockets that a player can fire.

What's a good way to programmatically manage the cloning of a base rocket, for example?

I can think of 2 ways to do it:

  • Player has a currently selected weapon (which is an int)
  • When player shoots, the selectedWeapon member is looked at, and the correct instance of rocket is created (with some base parameters)

Or

  • Player has a currently selected weapon (which is a pointer, to a "base instance" of the rocket object)
  • When player shoots, the base instance rocket is cloned, transformed, and shot into the game world
\$\endgroup\$
1
  • \$\begingroup\$ A clone is an exact copy. You don't want that ( transformation, state etc ). Perhaps it's a case of semantics. But you're question should just be about instantiating. \$\endgroup\$
    – Sidar
    Nov 21, 2012 at 18:08

2 Answers 2

2
\$\begingroup\$

In general terms, you're talking about the difference between the Factory pattern - a piece of code that creates objects based on being told which type to make - and the Prototype pattern - a piece of code that creates objects by copying an existing object.

In cases like this, I think the prototype pattern is the wrong way to go. A rocket will have several aspects (position, velocity, orientation, etc) which only make sense once it's in the world, and there are very few values that you would want to copy that are useful anyway. So to have a rocket object hanging around attached to the player with several values that are redundant feels like a poor approach. Your rockets probably contain no state that needs to be copied from a prototype, so just create them when needed and set up the values accordingly.

Where the prototype pattern is useful is when you want to be able to define cloneable objects from within the application - eg. a player can design his own rocket type, and then fire them later. Then it would make sense to store their design as a prototype.

\$\endgroup\$
0
\$\begingroup\$

The former makes slightly more sense. Think of weapons that fire multiple projectiles or random projectiles. Better to have data that defines what to fire and how and then use that rather than attaching a single object.

Besides, if the player had to hold and instance of a projectile to fire it, how and when do you set that up? Your weapon power ups and such will need some way of defining what projectile to give to the player, so by storing only the cloneable instance you'll only have moved the problem rather than having solved it.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .