0
votes

I'm coding a game in XNA and I have two subclasses (Character and Enemy). I wanted to create a method that would lower an enemy's health by the character attack score. How would I do that? I'm having issues with having classes interact with each other.

Would it be possible to do something similar to a constructor, where I could type in something like:

Attack(player.attack, enemy.health);

And if the player's attack score was 2, and the enemies health was 10, after invoking the method the enemy would have 8 health left.

2

2 Answers

1
votes

Probably cleaner to make Attack a method on the enemy class, then you can Attack the enemy using your player:

enemy.Attack(player);

The code in the Attack method on the enemy will look at the player.attack property, and decrement its own health accordingly.

1
votes

You might consider splitting this up a little. Example:

// Method on each player, which in turn calls the method below.
// This is called when myPlayer attacks enemyPlayer.
myPlayer.AttackPlayer(enemyPlayer); 


// Called from within the AttackPlayer method which was called on
// myPlayer. The parameter <damage> is a (private?) property in myPlayer:
enemyPlayer.ReceiveAttack(damage); 

This should make it fairly clear what is happening, and let you handle different aspects in a flexible way, in case you might want to expand this later.

Example: The player receiving the attack might behave differently in different situation (eg. receive less damage if he has armour, etc), without the attacker having to take this into consideration.