XNA Tutorials
| XNA Platformer Starter Kit - Adding Melee - Player.cs |
| Written by Jeff Brown | ||||||
Page 2 of 4
Player.cslt;span style="font-size: 10pt;">Find the following: private float jumpTime; After it add the following: // Attacking state public bool isAttacking; const float MaxAttackTime = 0.33f; public float AttackTime; Next find the following: public Rectangle BoundingRectangle { get { int left = (int)Math.Round(Position.X - sprite.Origin.X) + localBounds.X; int top = (int)Math.Round(Position.Y - sprite.Origin.Y) + localBounds.Y; return new Rectangle(left, top, localBounds.Width, localBounds.Height); } } After that add the following: public Rectangle MeleeRectangle { get { int left = (int)Math.Round(Position.X - sprite.Origin.X) + localBounds.X; int top = (int)Math.Round(Position.Y - sprite.Origin.Y) + localBounds.Y; if (flip == SpriteEffects.FlipHorizontally) return new Rectangle( (left + localBounds.Width), top, localBounds.Width, localBounds.Height); else return new Rectangle( (left - localBounds.Width), top, localBounds.Width, localBounds.Height); } } At the top of Player.cs find the following line: private Animation dieAnimation;
After that add the following line: private Animation attackAnimation;
dieAnimation = new Animation(Level.Content.Load<Texture2D>("Sprites/Player/Die"), 0.1f, false); After that add the following: attackAnimation = new Animation(Level.Content.Load<Texture2D>("Sprites/Player/Attack"), 0.1f, false);
private void DoAttack(GameTime gameTime) { // If the player wants to attack if (isAttacking) { // Begin or continue an attack if (AttackTime > 0.0f) { AttackTime -= (float)gameTime.ElapsedGameTime.TotalSeconds; sprite.PlayAnimation(attackAnimation); } else { isAttacking = false; } } else { //Continues not attack or cancels an attack in progress AttackTime = 0.0f; } }
class Player
{
KeyboardState previousKeyboardState = Keyboard.GetState();
if (previousKeyboardState.IsKeyUp(Keys.F) && keyboardState.IsKeyDown(Keys.F)) { if (AttackTime != MaxAttackTime) { isAttacking = true; AttackTime = MaxAttackTime; } }
DoAttack(gameTime);
if (IsAlive && IsOnGround) { if (Math.Abs(Velocity.X) - 0.02f > 0) { sprite.PlayAnimation(runAnimation); } else { sprite.PlayAnimation(idleAnimation); } }
if (IsAlive && IsOnGround) { if (isAttacking) { sprite.PlayAnimation(attackAnimation); } else { if (Math.Abs(Velocity.X) - 0.02f > 0) { sprite.PlayAnimation(runAnimation); } else { sprite.PlayAnimation(idleAnimation); } } }
Build the solution at this point to make sure you don’t have any errors. |