using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; namespace Jumpy { class Player { enum Facing { Left, Right }; enum Pose { Walking, Standing, Crouching, Stretching, SwordSwing }; private const int spriteSize = 144; private const int spriteWidth = 20; private const int moveSpeed = 600; private Texture2D texture; // TODO: stop assuming 1920x1080. private Vector2 position = new Vector2(200, 1080 - spriteSize / 2); private Facing facing = Facing.Right; private Pose pose = Pose.Standing; private double swordSwingTime = 0; public Player(Texture2D texture) { this.texture = texture; } public void Update(GameTime gameTime, GamePadState gamePad) { if (gamePad.Buttons.X == ButtonState.Pressed && swordSwingTime <= 0) { swordSwingTime = 0.3; pose = Pose.SwordSwing; return; } Vector2 leftStick = gamePad.ThumbSticks.Left; if (leftStick.X < -0.5) { facing = Facing.Left; pose = Pose.Walking; position.X -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; } else if (leftStick.X > 0.5) { facing = Facing.Right; pose = Pose.Walking; position.X += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; } else if (leftStick.Y < -0.5) { pose = Pose.Crouching; } else if (leftStick.Y > 0.5) { pose = Pose.Stretching; } else { pose = Pose.Standing; } if (swordSwingTime > 0) { swordSwingTime -= gameTime.ElapsedGameTime.TotalSeconds; pose = Pose.SwordSwing; } position.X = Math.Min(Math.Max(position.X, 0 + spriteWidth), 1920 - spriteWidth); } private Point spritePosition(Pose pose, GameTime time) { switch (pose) { case Pose.Walking: int frameNum = (time.TotalGameTime.Milliseconds / 125) % 4; if (frameNum == 3) { frameNum = 1; } return new Point(spriteSize * frameNum + spriteSize * 6, 0); case Pose.Crouching: return new Point(spriteSize * 7, spriteSize * 2); case Pose.Stretching: return new Point(spriteSize * 1, spriteSize * 2); case Pose.SwordSwing: if (swordSwingTime > 0.2) { return new Point(spriteSize * 3, 0); } else if (swordSwingTime > 0.1) { return new Point(spriteSize * 4, 0); } else { return new Point(spriteSize * 5, 0); } case Pose.Standing: default: return new Point(spriteSize * 7, 0); } } public void Draw(GameTime time, SpriteBatch spriteBatch) { Point source = spritePosition(pose, time); Rectangle textureSource = new Rectangle(source.X, source.Y, spriteSize, spriteSize); Vector2 spriteCenter = new Vector2(spriteSize / 2, spriteSize / 2); SpriteEffects effect = facing == Facing.Right ? SpriteEffects.FlipHorizontally : SpriteEffects.None; spriteBatch.Draw(texture, position, textureSource, Color.White, 0f, spriteCenter, Vector2.One, effect, 0f); } } }