TiledMapTilesetAnimatedTile.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using Microsoft.Xna.Framework;
  4. using Microsoft.Xna.Framework.Graphics;
  5. namespace MonoGame.Extended.Tiled
  6. {
  7. public class TiledMapTilesetAnimatedTile : TiledMapTilesetTile
  8. {
  9. private TimeSpan _timer = TimeSpan.Zero;
  10. private int _frameIndex;
  11. public ReadOnlyCollection<TiledMapTilesetTileAnimationFrame> AnimationFrames { get; }
  12. public TiledMapTilesetTileAnimationFrame CurrentAnimationFrame { get; private set; }
  13. public TiledMapTilesetAnimatedTile(int localTileIdentifier,
  14. TiledMapTilesetTileAnimationFrame[] frames, string type = null, TiledMapObject[] objects = null, Texture2D texture = null)
  15. : base(localTileIdentifier, type, objects, texture)
  16. {
  17. if (frames.Length == 0) throw new InvalidOperationException("There must be at least one tileset animation frame");
  18. AnimationFrames = new ReadOnlyCollection<TiledMapTilesetTileAnimationFrame>(frames);
  19. CurrentAnimationFrame = AnimationFrames[0];
  20. }
  21. public void CreateTextureRotations(TiledMapTileset tileset, TiledMapTileFlipFlags flipFlags)
  22. {
  23. for (int i = 0; i < AnimationFrames.Count; i++)
  24. {
  25. AnimationFrames[i].CreateTextureRotations(tileset, flipFlags);
  26. }
  27. }
  28. public void Update(GameTime gameTime)
  29. {
  30. _timer += gameTime.ElapsedGameTime;
  31. if (_timer <= CurrentAnimationFrame.Duration)
  32. return;
  33. _timer -= CurrentAnimationFrame.Duration;
  34. _frameIndex = (_frameIndex + 1) % AnimationFrames.Count;
  35. CurrentAnimationFrame = AnimationFrames[_frameIndex];
  36. }
  37. }
  38. }