Search code examples
c#animationxnamonogame

Animation won't work in XNA


I made class that cut's portion of large spritesheet and draws it on screen. And i managed to draw that part of sceen just it wont animate.

    public AnimatedSprite(Vector2 position, string texture)
    {
        sPostion = position;
        sTexture = Asset_Manager.GetInstance().texture[texture];
}

    /// <summary>
    /// Adds an animation to the AnimatedSprite
    /// </summary>
    public void AddAnimation(int frames, int yPos, int xStartFrame, string name, int width, int height, Vector2 offset)
    {

        //Creates an array of rectangles which will be used when playing an animation
        Rectangle[] Rectangles = new Rectangle[frames];

        //Fills up the array of rectangles
        for (int i = 0; i < frames; i++)
        {
            Rectangles[i] = new Rectangle((i + xStartFrame) * width, yPos, width, height);
        }
        sAnimations.Add(name, Rectangles);
        sOffsets.Add(name, offset);
    }

    /// <summary>
    /// Determines when we have to change frames
    /// </summary>
    /// <param name="GameTime">GameTime</param>
    public virtual void Update(GameTime gameTime)
    {

        timeElapsed += gameTime.ElapsedGameTime.TotalSeconds;


        if (timeElapsed > timeToUpdate)
        {

            timeElapsed -= timeToUpdate;


            if (frameIndex < sAnimations[currentAnimation].Length - 1)
            {
                frameIndex++;
            }
            else //Restarts the animation
            { 
                frameIndex = 0;
            }
        }
    }


    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(sTexture, sPostion, sAnimations[currentAnimation][frameIndex], Color.White);
    }

    public void PlayAnimation(string name)
    {

        if (currentAnimation != name)
        {
            currentAnimation = name;

        }
    }


}

}

Animation Class .

Player Class

It won't loop animations.

public class Player
{

    AnimatedSprite player;

    public Player()
    {

        player = new AnimatedSprite(new Vector2(100,100),"Ships");
        player.AddAnimation(2, 0, 1, "GreenPlane", 25, 26, new Vector2(0, 0));
        player.PlayAnimation("GreenPlane");
    }
    public void Update(GameTime gameTime)
    {
        player.Update(gameTime);   
    }
    public void Draw(SpriteBatch spriteBach)
    {
        player.Draw(spriteBach);
    }

it draws first frame and it wont change form frame 1 to frame x and loop back,


Solution

  • Asked 5 days ago, so i think you already got a solution..

    If not: Your code looks fine to me. I put your code to work in a test project and it updates and renders just fine. In your snippet you call .Update(GameTime) on player (of type AnimatedSprite), but did you also call .Update(GameTime) on the player instance (of type Player) itself?

    -

    i tried it with your linked classes and 'pure' xna - not mono