AnimatingSprite.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // AnimatingSprite.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using System.Collections.Generic;
  12. using Microsoft.Xna.Framework;
  13. using Microsoft.Xna.Framework.Content;
  14. using Microsoft.Xna.Framework.Graphics;
  15. #endregion
  16. namespace RolePlayingGameData
  17. {
  18. /// <summary>
  19. /// A sprite sheet with flipbook-style animations.
  20. /// </summary>
  21. public class AnimatingSprite : ContentObject
  22. #if WINDOWS
  23. , ICloneable
  24. #endif
  25. {
  26. #region Graphics Data
  27. /// <summary>
  28. /// The content path and name of the texture for this spell animation.
  29. /// </summary>
  30. private string textureName;
  31. /// <summary>
  32. /// The content path and name of the texture for this spell animation.
  33. /// </summary>
  34. public string TextureName
  35. {
  36. get { return textureName; }
  37. set { textureName = value; }
  38. }
  39. /// <summary>
  40. /// The texture for this spell animation.
  41. /// </summary>
  42. private Texture2D texture;
  43. /// <summary>
  44. /// The texture for this spell animation.
  45. /// </summary>
  46. [ContentSerializerIgnore]
  47. public Texture2D Texture
  48. {
  49. get { return texture; }
  50. set { texture = value; }
  51. }
  52. #endregion
  53. #region Frame Data
  54. /// <summary>
  55. /// The dimensions of a single frame of animation.
  56. /// </summary>
  57. private Point frameDimensions;
  58. /// <summary>
  59. /// The width of a single frame of animation.
  60. /// </summary>
  61. public Point FrameDimensions
  62. {
  63. get { return frameDimensions; }
  64. set
  65. {
  66. frameDimensions = value;
  67. frameOrigin.X = frameDimensions.X / 2;
  68. frameOrigin.Y = frameDimensions.Y / 2;
  69. }
  70. }
  71. /// <summary>
  72. /// The origin of the sprite, within a frame.
  73. /// </summary>
  74. private Point frameOrigin;
  75. /// <summary>
  76. /// The number of frames in a row in this sprite.
  77. /// </summary>
  78. private int framesPerRow;
  79. /// <summary>
  80. /// The number of frames in a row in this sprite.
  81. /// </summary>
  82. public int FramesPerRow
  83. {
  84. get { return framesPerRow; }
  85. set { framesPerRow = value; }
  86. }
  87. /// <summary>
  88. /// The offset of this sprite from the position it's drawn at.
  89. /// </summary>
  90. private Vector2 sourceOffset;
  91. /// <summary>
  92. /// The offset of this sprite from the position it's drawn at.
  93. /// </summary>
  94. [ContentSerializer(Optional=true)]
  95. public Vector2 SourceOffset
  96. {
  97. get { return sourceOffset; }
  98. set { sourceOffset = value; }
  99. }
  100. #endregion
  101. #region Animation Data
  102. /// <summary>
  103. /// The animations defined for this sprite.
  104. /// </summary>
  105. private List<Animation> animations = new List<Animation>();
  106. /// <summary>
  107. /// The animations defined for this sprite.
  108. /// </summary>
  109. public List<Animation> Animations
  110. {
  111. get { return animations; }
  112. set { animations = value; }
  113. }
  114. /// <summary>
  115. /// Enumerate the animations on this animated sprite.
  116. /// </summary>
  117. /// <param name="animationName">The name of the animation.</param>
  118. /// <returns>The animation if found; null otherwise.</returns>
  119. public Animation this[string animationName]
  120. {
  121. get
  122. {
  123. if (String.IsNullOrEmpty(animationName))
  124. {
  125. return null;
  126. }
  127. foreach (Animation animation in animations)
  128. {
  129. if (String.Compare(animation.Name, animationName, StringComparison.OrdinalIgnoreCase) == 0)
  130. {
  131. return animation;
  132. }
  133. }
  134. return null;
  135. }
  136. }
  137. /// <summary>
  138. /// Add the animation to the list, checking for name collisions.
  139. /// </summary>
  140. /// <returns>True if the animation was added to the list.</returns>
  141. public bool AddAnimation(Animation animation)
  142. {
  143. if ((animation != null) && (this[animation.Name] == null))
  144. {
  145. animations.Add(animation);
  146. return true;
  147. }
  148. return false;
  149. }
  150. #endregion
  151. #region Playback
  152. /// <summary>
  153. /// The animation currently playing back on this sprite.
  154. /// </summary>
  155. private Animation currentAnimation = null;
  156. /// <summary>
  157. /// The current frame in the current animation.
  158. /// </summary>
  159. private int currentFrame;
  160. /// <summary>
  161. /// The elapsed time since the last frame switch.
  162. /// </summary>
  163. private float elapsedTime;
  164. /// <summary>
  165. /// The source rectangle of the current frame of animation.
  166. /// </summary>
  167. private Rectangle sourceRectangle;
  168. /// <summary>
  169. /// The source rectangle of the current frame of animation.
  170. /// </summary>
  171. public Rectangle SourceRectangle
  172. {
  173. get { return sourceRectangle; }
  174. }
  175. /// <summary>
  176. /// Play the given animation on the sprite.
  177. /// </summary>
  178. /// <remarks>The given animation may be null, to clear any animation.</remarks>
  179. public void PlayAnimation(Animation animation)
  180. {
  181. // start the new animation, ignoring redundant Plays
  182. if (animation != currentAnimation)
  183. {
  184. currentAnimation = animation;
  185. ResetAnimation();
  186. }
  187. }
  188. /// <summary>
  189. /// Play an animation given by index.
  190. /// </summary>
  191. public void PlayAnimation(int index)
  192. {
  193. // check the parameter
  194. if ((index < 0) || (index >= animations.Count))
  195. {
  196. throw new ArgumentOutOfRangeException("index");
  197. }
  198. PlayAnimation(this.animations[index]);
  199. }
  200. /// <summary>
  201. /// Play an animation given by name.
  202. /// </summary>
  203. public void PlayAnimation(string name)
  204. {
  205. // check the parameter
  206. if (String.IsNullOrEmpty(name))
  207. {
  208. throw new ArgumentNullException("name");
  209. }
  210. PlayAnimation(this[name]);
  211. }
  212. /// <summary>
  213. /// Play a given animation name, with the given direction suffix.
  214. /// </summary>
  215. /// <example>
  216. /// For example, passing "Walk" and Direction.South will play the animation
  217. /// named "WalkSouth".
  218. /// </example>
  219. public void PlayAnimation(string name, Direction direction)
  220. {
  221. // check the parameter
  222. if (String.IsNullOrEmpty(name))
  223. {
  224. throw new ArgumentNullException("name");
  225. }
  226. PlayAnimation(name + direction.ToString());
  227. }
  228. /// <summary>
  229. /// Reset the animation back to its starting position.
  230. /// </summary>
  231. public void ResetAnimation()
  232. {
  233. elapsedTime = 0f;
  234. if (currentAnimation != null)
  235. {
  236. currentFrame = currentAnimation.StartingFrame;
  237. // calculate the source rectangle by updating the animation
  238. UpdateAnimation(0f);
  239. }
  240. }
  241. /// <summary>
  242. /// Advance the current animation to the final sprite.
  243. /// </summary>
  244. public void AdvanceToEnd()
  245. {
  246. if (currentAnimation != null)
  247. {
  248. currentFrame = currentAnimation.EndingFrame;
  249. // calculate the source rectangle by updating the animation
  250. UpdateAnimation(0f);
  251. }
  252. }
  253. /// <summary>
  254. /// Stop any animation playing on the sprite.
  255. /// </summary>
  256. public void StopAnimation()
  257. {
  258. currentAnimation = null;
  259. }
  260. /// <summary>
  261. /// Returns true if playback on the current animation is complete, or if
  262. /// there is no animation at all.
  263. /// </summary>
  264. public bool IsPlaybackComplete
  265. {
  266. get
  267. {
  268. return ((currentAnimation == null) ||
  269. (!currentAnimation.IsLoop &&
  270. (currentFrame > currentAnimation.EndingFrame)));
  271. }
  272. }
  273. #endregion
  274. #region Updating
  275. /// <summary>
  276. /// Update the current animation.
  277. /// </summary>
  278. public void UpdateAnimation(float elapsedSeconds)
  279. {
  280. if (IsPlaybackComplete)
  281. {
  282. return;
  283. }
  284. // loop the animation if needed
  285. if (currentAnimation.IsLoop && (currentFrame > currentAnimation.EndingFrame))
  286. {
  287. currentFrame = currentAnimation.StartingFrame;
  288. }
  289. // update the source rectangle
  290. int column = (currentFrame - 1) / framesPerRow;
  291. sourceRectangle = new Rectangle(
  292. (currentFrame - 1 - (column * framesPerRow)) * frameDimensions.X,
  293. column * frameDimensions.Y,
  294. frameDimensions.X, frameDimensions.Y);
  295. // update the elapsed time
  296. elapsedTime += elapsedSeconds;
  297. // advance to the next frame if ready
  298. while (elapsedTime * 1000f > (float)currentAnimation.Interval)
  299. {
  300. currentFrame++;
  301. elapsedTime -= (float)currentAnimation.Interval / 1000f;
  302. }
  303. }
  304. #endregion
  305. #region Drawing
  306. /// <summary>
  307. /// Draw the sprite at the given position.
  308. /// </summary>
  309. /// <param name="spriteBatch">The SpriteBatch object used to draw.</param>
  310. /// <param name="position">The position of the sprite on-screen.</param>
  311. /// <param name="layerDepth">The depth at which the sprite is drawn.</param>
  312. public void Draw(SpriteBatch spriteBatch, Vector2 position, float layerDepth)
  313. {
  314. Draw(spriteBatch, position, layerDepth, SpriteEffects.None);
  315. }
  316. /// <summary>
  317. /// Draw the sprite at the given position.
  318. /// </summary>
  319. /// <param name="spriteBatch">The SpriteBatch object used to draw.</param>
  320. /// <param name="position">The position of the sprite on-screen.</param>
  321. /// <param name="layerDepth">The depth at which the sprite is drawn.</param>
  322. /// <param name="spriteEffect">The sprite-effect applied.</param>
  323. public void Draw(SpriteBatch spriteBatch, Vector2 position, float layerDepth,
  324. SpriteEffects spriteEffect)
  325. {
  326. // check the parameters
  327. if (spriteBatch == null)
  328. {
  329. throw new ArgumentNullException("spriteBatch");
  330. }
  331. if (texture != null)
  332. {
  333. spriteBatch.Draw(texture, position, sourceRectangle, Color.White, 0f,
  334. sourceOffset, 1f, spriteEffect,
  335. MathHelper.Clamp(layerDepth, 0f, 1f));
  336. }
  337. }
  338. #endregion
  339. #region Content Type Reader
  340. /// <summary>
  341. /// Read an AnimatingSprite object from the content pipeline.
  342. /// </summary>
  343. public class AnimatingSpriteReader : ContentTypeReader<AnimatingSprite>
  344. {
  345. /// <summary>
  346. /// Read an AnimatingSprite object from the content pipeline.
  347. /// </summary>
  348. protected override AnimatingSprite Read(ContentReader input,
  349. AnimatingSprite existingInstance)
  350. {
  351. AnimatingSprite animatingSprite = existingInstance;
  352. if (animatingSprite == null)
  353. {
  354. animatingSprite = new AnimatingSprite();
  355. }
  356. animatingSprite.AssetName = input.AssetName;
  357. animatingSprite.TextureName = input.ReadString();
  358. animatingSprite.Texture =
  359. input.ContentManager.Load<Texture2D>(
  360. System.IO.Path.Combine(@"Textures",
  361. animatingSprite.TextureName));
  362. animatingSprite.FrameDimensions = input.ReadObject<Point>();
  363. animatingSprite.FramesPerRow = input.ReadInt32();
  364. animatingSprite.SourceOffset = input.ReadObject<Vector2>();
  365. animatingSprite.Animations.AddRange(
  366. input.ReadObject<List<Animation>>());
  367. return animatingSprite;
  368. }
  369. }
  370. #endregion
  371. #region ICloneable Members
  372. /// <summary>
  373. /// Creates a clone of this object.
  374. /// </summary>
  375. public object Clone()
  376. {
  377. AnimatingSprite animatingSprite = new AnimatingSprite();
  378. animatingSprite.animations.AddRange(animations);
  379. animatingSprite.currentAnimation = currentAnimation;
  380. animatingSprite.currentFrame = currentFrame;
  381. animatingSprite.elapsedTime = elapsedTime;
  382. animatingSprite.frameDimensions = frameDimensions;
  383. animatingSprite.frameOrigin = frameOrigin;
  384. animatingSprite.framesPerRow = framesPerRow;
  385. animatingSprite.sourceOffset = sourceOffset;
  386. animatingSprite.sourceRectangle = sourceRectangle;
  387. animatingSprite.texture = texture;
  388. animatingSprite.textureName = textureName;
  389. return animatingSprite;
  390. }
  391. #endregion
  392. }
  393. }