I am making a game, and the animation class I made with 8 frames worked fine, but when I added 2 more frames, it messed up. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace Cubiez
{
class Player
{
public Texture2D playerTexture;
private Rectangle playerRect;
public Vector2 playerPosition;
public Vector2 origin;
public Vector2 velocity;
public int currentFrame;
public int frameHeight;
public int frameWidth;
float timer;
float interval = 150;
bool hasJumped;
public Player(Texture2D newPlayerTexture, Vector2 NewPosition, int newFrameHeight, int newFrameWidth)
{
playerPosition = NewPosition;
playerTexture = newPlayerTexture;
frameHeight = newFrameHeight;
frameWidth = newFrameWidth;
hasJumped = true;
}
public void Update(GameTime gameTime)
{
playerPosition += velocity;
playerRect = new Rectangle(currentFrame * frameWidth, 0, frameWidth, frameHeight);
origin = new Vector2(playerRect.Width / 2, playerRect.Height / 2);
playerPosition = playerPosition + velocity;
if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
velocity.X = 2f;
AnimateRight(gameTime);
}
else if (Keyboard.GetState().IsKeyDown(Keys.Left))
{
velocity.X = -2f;
AnimateLeft(gameTime);
}
else
{
velocity.X = 0f;
}
if (Keyboard.GetState().IsKeyDown(Keys.Space) && hasJumped == false)
{
playerPosition.Y -= 3f;
velocity.Y = -4.5f;
hasJumped = true;
}
if (hasJumped == true)
{
float i = 1;
velocity.Y += 0.15f * i;
}
if (playerPosition.Y + playerRect.Height >= 450)
{
hasJumped = false;
}
if (hasJumped == false)
{
velocity.Y = 0f;
}
}
public void AnimateRight(GameTime gameTime)
{
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
currentFrame++;
timer = 0;
if (currentFrame > 3)
{
currentFrame = 0;
}
}
}
public void AnimateLeft(GameTime gameTime)
{
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
currentFrame++;
timer = 0;
if (currentFrame > 6 || currentFrame < 3)
{
currentFrame = 6;
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(playerTexture, playerPosition, playerRect, Color.White, 0f, origin, 1.0f, SpriteEffects.None, 0);
spriteBatch.End();
}
}
}
When I move right, the player animates perfectly, but when I move left, depending on what I change the numbers in the
if (currentFrame > 6 || currentFrame < 3)
{
currentFrame = 6;
}
to, it either is no animation on one frame, or it turns right when he moves, or the player only animates part of it. If somebody could tell me what I am doing wrong, I would greatly apprieciate it. Thanks in advance :) Here is the image:
