Hyluss

[Monogame PingPong] AnimetedSprite

Oct 30th, 2018
564
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.97 KB | None | 0 0
  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.  
  9. namespace PingPong
  10. {
  11.     public class AnimatedSprite : Sprite
  12.     {
  13.         public int Rows, Columns;
  14.         int _currentFrame, _totalFrames;
  15.  
  16.         int _width, _height;
  17.  
  18.         int timeSinceLastFrame = 0;
  19.         int milisecondsPerFrame;
  20.  
  21.         public AnimatedSprite(Texture2D texture, int rows, int columns,int missingFrames, int msecondsPerFrame) : base(texture)
  22.         {
  23.             milisecondsPerFrame = msecondsPerFrame;
  24.             Rows = rows;
  25.             Columns = columns;
  26.             _currentFrame = 0;
  27.             _totalFrames = Rows * Columns - missingFrames;
  28.  
  29.             _width = texture.Width / Columns;
  30.             _height = texture.Height / Rows;
  31.  
  32.             base._textureWidth = _width;
  33.             base._textureHeight = _height;
  34.         }
  35.  
  36.         public override void Update(GameTime gameTime, List<Sprite> sprites)
  37.         {
  38.             timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
  39.             if (timeSinceLastFrame > milisecondsPerFrame)
  40.             {
  41.                 timeSinceLastFrame -= milisecondsPerFrame;
  42.  
  43.                 _currentFrame++;                
  44.                 if (_currentFrame == _totalFrames)
  45.                     _currentFrame = 0;
  46.             }
  47.         }
  48.  
  49.         public override void Draw(SpriteBatch spriteBatch)
  50.         {            
  51.             int row = (int)((float)_currentFrame / (float)Columns);
  52.             int column = _currentFrame % Columns;
  53.  
  54.             Rectangle sourceRectangle = new Rectangle(_width * column, _height * row, _width, _height);
  55.             Rectangle destinationRectangle = new Rectangle((int)base.Position.X, (int)base.Position.Y, _width, _height);
  56.  
  57.             spriteBatch.Draw(base._texture, destinationRectangle, sourceRectangle, Color.White);
  58.         }
  59.     }
  60. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment