XNA Adding Melee Attack

Adding melee attacks to the Platformer game that is provided in the XNA studio can be done in a very simple way. There are a few preliminary steps before you get started.

First you need an attack animation. A good length to make the animation would be 3 frames, I shortened the run animation and took the 4th 5th and 6th frame and drew in a sword. Second you need an attack sound , you can other go out on the internet and find a light saber sound or just use the jump sound and copy it. Import the two new assets and load them into the player class and your ready to go.

To make this as simple as possible, all you want to do is mimic the jump code. At the top of player, define a bool labeled IsAttacking, then make a public read only property for it. Create a const float for MaxAttackTime = 0.33f, and create a float for AttackTime.

In the function that reads player input, create previous states for both the gamepadstate and the keyboardstate. Then create an if statement checking if the previous gamepad/keyboard state does not have x pressed and the current gamepad/keyboard state does have x pressed, then set IsAttacking to true.

Inside the Update function in player, add a function called DoAttack to make the player attack. (similar to the apply physics function)

Then Declare DoAttack passing in the gametime. In this function you want to check if the player IsAttacking then play the attack sound and set attack time equal to max attack time. Create a second if statement to check if attack time is greater then zero, then play the attack animation (Note this plays fame only when this function is called so this needs to be called each update) and subtract gametime from attacktime else set is attacking to zero.

Finally you need to kill the enemy. To do this you need to go into the level class and use the code for the power up tutorial (found at http://msdn.microsoft.com/en-us/library/dd254920.aspx ) add or Player.IsAttacking to the if statement checking weather the play kills the enemy.

That’s it. You should have a fully functional attack and able to kill the enemies (Note if they are not playing death animations and sounds please do the rest of the Power Up Tutorial)

Please leave comments if you want to see code samples or have questions.


Note: Only a member of this blog may post a comment.