Ball.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.Xna.Framework;
  7. using Microsoft.Xna.Framework.Graphics;
  8. using Microsoft.Xna.Framework.Input;
  9. namespace Tutorial010.Sprites
  10. {
  11. public class Ball : Sprite
  12. {
  13. private float _timer = 0f; // Incrementing the speed over time
  14. private Vector2? _startPosition = null;
  15. private float? _startSpeed;
  16. private bool _isPlaying;
  17. public Score Score;
  18. public int SpeedIncrementSpan = 10; // How often the speed will increment
  19. public Ball(Texture2D texture)
  20. : base(texture)
  21. {
  22. Speed = 3f;
  23. }
  24. public override void Update(GameTime gameTime, List<Sprite> sprites)
  25. {
  26. if (_startPosition == null)
  27. {
  28. _startPosition = Position;
  29. _startSpeed = Speed;
  30. Restart();
  31. }
  32. if (Keyboard.GetState().IsKeyDown(Keys.Space))
  33. _isPlaying = true;
  34. if (!_isPlaying)
  35. return;
  36. _timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
  37. if (_timer > SpeedIncrementSpan)
  38. {
  39. Speed++;
  40. _timer = 0;
  41. }
  42. foreach (var sprite in sprites)
  43. {
  44. if (sprite == this)
  45. continue;
  46. if (this.Velocity.X > 0 && this.IsTouchingLeft(sprite))
  47. this.Velocity.X = -this.Velocity.X;
  48. if (this.Velocity.X < 0 && this.IsTouchingRight(sprite))
  49. this.Velocity.X = -this.Velocity.X;
  50. if (this.Velocity.Y > 0 && this.IsTouchingTop(sprite))
  51. this.Velocity.Y = -this.Velocity.Y;
  52. if (this.Velocity.Y < 0 && this.IsTouchingBottom(sprite))
  53. this.Velocity.Y = -this.Velocity.Y;
  54. }
  55. if (Position.Y <= 0 || Position.Y + _texture.Height >= Game1.ScreenHeight)
  56. Velocity.Y = -Velocity.Y;
  57. if (Position.X <= 0)
  58. {
  59. Score.Score2++;
  60. Restart();
  61. }
  62. if (Position.X + _texture.Width >= Game1.ScreenWidth)
  63. {
  64. Score.Score1++;
  65. Restart();
  66. }
  67. Position += Velocity * Speed;
  68. }
  69. public void Restart()
  70. {
  71. var direction = Game1.Random.Next(0, 4);
  72. switch (direction)
  73. {
  74. case 0:
  75. Velocity = new Vector2(1, 1);
  76. break;
  77. case 1:
  78. Velocity = new Vector2(1, -1);
  79. break;
  80. case 2:
  81. Velocity = new Vector2(-1, -1);
  82. break;
  83. case 3:
  84. Velocity = new Vector2(-1, 1);
  85. break;
  86. }
  87. Position = (Vector2)_startPosition;
  88. Speed = (float)_startSpeed;
  89. _timer = 0;
  90. _isPlaying = false;
  91. }
  92. }
  93. }