ScrollingBackground.cs 2.6 KB

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