I am having trouble reading a spritesheet with rows and columns. If it is just one row, then my code works fine. The sheet looks like this:
Source: Character animations, clothes, armor, weapons, skeleton enemy, combat dummy
Right now, it only works with the first row. I can't figure out how to move it down to the next row. I know I have to change my SourceRect
for the x
and y
but don't know to what.
Here's my code:
class SpriteSheet
{
public Texture2D Texture { get; set; }
public Vector2 Origin { get; set; }
public Rectangle SourceRect { get; set; }
public Vector2 position;
private float timer, interval;
private int currentFrame;
private int spriteWidth, spriteHeight, spriteSpeed;
private int rows, columns;
private KeyboardState currentKBState, previousKBState;
public SpriteSheet(Texture2D texture, int spriteWidth, int spriteHeight, int rows = 1, int columns = 0, int currentFrame = 1)
{
Texture = texture;
this.currentFrame = currentFrame;
this.spriteWidth = spriteWidth;
this.spriteHeight = spriteHeight;
this.rows = rows;
this.columns = columns;
spriteSpeed = 100;
interval = 200;
}
// Handle movement of sprite
public void Update(GameTime gameTime)
{
previousKBState = currentKBState;
currentKBState = Keyboard.GetState();
// Get the sprite from the sheet
// THIS LINE NEEDS TO BE CHANGED I THINK
SourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);
if(currentKBState.GetPressedKeys().Length == 0)
{
if (currentFrame > 0 && currentFrame < 9)
currentFrame = 0;
if (currentFrame > 9 && currentFrame < 18)
currentFrame = 9;
if (currentFrame > 18 && currentFrame < 27)
currentFrame = 18;
if (currentFrame > 27 && currentFrame < 36)
currentFrame = 27;
}
// Animate Up
if (currentKBState.IsKeyDown(Keys.Up))
{
AnimateUp(gameTime);
// Check boundary
if (position.Y > 25)
position.Y -= (float) (spriteSpeed * gameTime.ElapsedGameTime.TotalSeconds);
}
}
private void AnimateUp(GameTime gameTime)
{
if (currentKBState != previousKBState)
currentFrame = 1;
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if(timer > interval)
{
currentFrame++;
if (currentFrame > 8)
currentFrame = 0;
timer = 0f;
}
}
}