ScrollingBackground.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Tutorial023.Sprites;
  9. namespace Tutorial023.Misc
  10. {
  11. public class ScrollingBackground : Component
  12. {
  13. private bool _constantSpeed;
  14. private float _layer;
  15. private float _scrollingSpeed;
  16. private List<Sprite> _sprites;
  17. private readonly Player _player;
  18. private float _speed;
  19. public float Layer
  20. {
  21. get { return _layer; }
  22. set
  23. {
  24. _layer = value;
  25. foreach (var sprite in _sprites)
  26. sprite.Layer = _layer;
  27. }
  28. }
  29. public ScrollingBackground(Texture2D texture, Player player, float scrollingSpeed, bool constantSpeed = false)
  30. : this(new List<Texture2D>() { texture, texture }, player, scrollingSpeed, constantSpeed)
  31. {
  32. }
  33. public ScrollingBackground(List<Texture2D> textures, Player player, float scrollingSpeed, bool constantSpeed = false)
  34. {
  35. _player = player;
  36. _sprites = new List<Sprite>();
  37. for (int i = 0; i < textures.Count; i++)
  38. {
  39. var texture = textures[i];
  40. _sprites.Add(new Sprite(texture)
  41. {
  42. Position = new Vector2(i * texture.Width - Math.Min(i, i + 1), Game1.ScreenHeight - texture.Height),
  43. });
  44. }
  45. _scrollingSpeed = scrollingSpeed;
  46. _constantSpeed = constantSpeed;
  47. }
  48. public override void Update(GameTime gameTime)
  49. {
  50. ApplySpeed(gameTime);
  51. CheckPosition();
  52. }
  53. private void ApplySpeed(GameTime gameTime)
  54. {
  55. _speed = (float)(_scrollingSpeed * gameTime.ElapsedGameTime.TotalSeconds);
  56. if (!_constantSpeed || _player.Velocity.X > 0)
  57. _speed *= _player.Velocity.X;
  58. foreach (var sprite in _sprites)
  59. {
  60. sprite.Position.X -= _speed;
  61. }
  62. }
  63. private void CheckPosition()
  64. {
  65. for (int i = 0; i < _sprites.Count; i++)
  66. {
  67. var sprite = _sprites[i];
  68. if (sprite.Rectangle.Right <= 0)
  69. {
  70. var index = i - 1;
  71. if (index < 0)
  72. index = _sprites.Count - 1;
  73. sprite.Position.X = _sprites[index].Rectangle.Right - (_speed * 2);
  74. }
  75. }
  76. }
  77. public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  78. {
  79. foreach (var sprite in _sprites)
  80. sprite.Draw(gameTime, spriteBatch);
  81. }
  82. }
  83. }