Clouds.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using AtomicEngine;
  3. public class Clouds
  4. {
  5. private int _currentIndex;
  6. private readonly int _range;
  7. private readonly int _deviation;
  8. private readonly int _minY;
  9. private readonly Node[] _clouds;
  10. private readonly Random rng = new Random();
  11. public Clouds(float startX, int minY, int deviation, int amount, int range)
  12. {
  13. _minY = minY;
  14. _deviation = deviation;
  15. _range = range;
  16. Sprite2D[] cloudSprites = {
  17. Cache.Get<Sprite2D>("scenarios/cloud1.png"),
  18. Cache.Get<Sprite2D>("scenarios/cloud2.png"),
  19. Cache.Get<Sprite2D>("scenarios/cloud3.png")};
  20. // We pre-fill the screen with clouds
  21. float cloudSpacing = range*2/amount;
  22. _clouds = new Node[amount];
  23. for (int i = 0; i < amount; i++)
  24. {
  25. _clouds[i] = AtomicMain.CreateSpriteNode(cloudSprites[rng.Next(cloudSprites.Length)], 4, false);
  26. RecycleCloud(startX-=cloudSpacing, _clouds[i]);
  27. }
  28. }
  29. private void RecycleCloud(float currentX, Node cloud)
  30. {
  31. // Position cloud at rightmost edge of the range
  32. cloud.SetPosition(new Vector3(currentX+_range, rng.Next(_deviation) + _minY, 15));
  33. }
  34. public void Tick(float dt, float currentX)
  35. {
  36. // We lazily check clouds and recycle them
  37. _currentIndex++;
  38. Node currentCloud = _clouds[_currentIndex%_clouds.Length];
  39. if (currentCloud.Position.X < currentX - _range)
  40. {
  41. RecycleCloud(currentX, currentCloud);
  42. }
  43. // We translate all clouds according to their height
  44. foreach (Node cloud in _clouds)
  45. {
  46. cloud.Translate2D(-Vector2.UnitX*dt*((cloud.Position2D.Y-_minY)*0.3f+1));
  47. }
  48. }
  49. }