Sprite.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using Microsoft.Xna.Framework.Input;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using Tutorial011.Managers;
  10. using Tutorial011.Models;
  11. namespace Tutorial011.Sprites
  12. {
  13. public class Sprite
  14. {
  15. #region Fields
  16. protected AnimationManager _animationManager;
  17. protected Dictionary<string, Animation> _animations;
  18. protected Vector2 _position;
  19. protected Texture2D _texture;
  20. #endregion
  21. #region Properties
  22. public Input Input;
  23. public Vector2 Position
  24. {
  25. get { return _position; }
  26. set
  27. {
  28. _position = value;
  29. if (_animationManager != null)
  30. _animationManager.Position = _position;
  31. }
  32. }
  33. public float Speed = 1f;
  34. public Vector2 Velocity;
  35. #endregion
  36. #region Methods
  37. public virtual void Draw(SpriteBatch spriteBatch)
  38. {
  39. if (_texture != null)
  40. spriteBatch.Draw(_texture, Position, Color.White);
  41. else if (_animationManager != null)
  42. _animationManager.Draw(spriteBatch);
  43. else throw new Exception("This ain't right..!");
  44. }
  45. public virtual void Move()
  46. {
  47. if (Keyboard.GetState().IsKeyDown(Input.Up))
  48. Velocity.Y = -Speed;
  49. else if (Keyboard.GetState().IsKeyDown(Input.Down))
  50. Velocity.Y = Speed;
  51. else if (Keyboard.GetState().IsKeyDown(Input.Left))
  52. Velocity.X = -Speed;
  53. else if (Keyboard.GetState().IsKeyDown(Input.Right))
  54. Velocity.X = Speed;
  55. }
  56. protected virtual void SetAnimations()
  57. {
  58. if (Velocity.X > 0)
  59. _animationManager.Play(_animations["WalkRight"]);
  60. else if (Velocity.X < 0)
  61. _animationManager.Play(_animations["WalkLeft"]);
  62. else if (Velocity.Y > 0)
  63. _animationManager.Play(_animations["WalkDown"]);
  64. else if (Velocity.Y < 0)
  65. _animationManager.Play(_animations["WalkUp"]);
  66. else _animationManager.Stop();
  67. }
  68. public Sprite(Dictionary<string, Animation> animations)
  69. {
  70. _animations = animations;
  71. _animationManager = new AnimationManager(_animations.First().Value);
  72. }
  73. public Sprite(Texture2D texture)
  74. {
  75. _texture = texture;
  76. }
  77. public virtual void Update(GameTime gameTime, List<Sprite> sprites)
  78. {
  79. Move();
  80. SetAnimations();
  81. _animationManager.Update(gameTime);
  82. Position += Velocity;
  83. Velocity = Vector2.Zero;
  84. }
  85. #endregion
  86. }
  87. }