2
\$\begingroup\$

I have 2 different classes, a EnemyFighter class, and a EnemyBomber class. both are planes that I have that can fly around the map.( i also have AllyFighter, and AllyBomber)

So far they can follow me, and eachother, but how would I set up a target variable or something?

like I could set up a target variable for the enemyfighter

AllyFighter target;

and a variable holding the location of the allyfighter as a Vector2.

but then what if I want to target an AllyBomber? do I have to make 2 variables? or is there some other approach I should take?

Thanks

EDIT: Maybe a better question would be how can I target different enemy types (ones with different classes)? or at least hold there information in a 'target' variable

\$\endgroup\$
1
  • 1
    \$\begingroup\$ If you absolutely need to split those units up into separate classes you should look into polymorphism: en.wikipedia.org/wiki/… \$\endgroup\$ Sep 23, 2013 at 21:01

1 Answer 1

3
\$\begingroup\$

Ideally you'd have some parent class that all these classes inherit from. For example, if all of your planes inherited from Plane, then you could easily create a list of those different classes with something like:

List<Plane> targets = new List<Plane>();

Now you can add all your targets to the same list. Of course you can just have a single target too:

Plane target;

And then as long as AllyFighter, AllyBomber and so on all extend Plane, you can use the same variable.

Do note that you will only be able to access the data that's commonly stored your targets at the Plane level (apart from casting the object to the correct type). This means you'll want to store the important information for targeting at the Plane level (you likely would anyway since most of the information is going to be common to them all). So stuff like position, health, armor, etc. should be data inside Plane not inside AllyBomber.

\$\endgroup\$

You must log in to answer this question.

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