Untitled

 avatar
unknown
csharp
10 days ago
2.1 kB
2
Indexable
using System.Collections.Generic;

using Microsoft.Xna.Framework;

public class Animator
{
    private Dictionary<string, Rectangle[]> _animations;
    private string _currentAnimation;
    private int _currentFrame;
    private float _frameTime;
    private float _timer;
    private bool _isPlaying;

    public Animator()
    {
        _animations = new Dictionary<string, Rectangle[]>();
        _currentAnimation = string.Empty;
        _currentFrame = 0;
        _frameTime = 0.1f; // Default frame duration in seconds
        _timer = 0f;
        _isPlaying = false;
    }

    public void AddAnimation(string name, Rectangle[] frames)
    {
        _animations[name] = frames;
    }

    public void PlayAnimation(string name, float frameDuration = 0.1f)
    {
        if (_currentAnimation == name)
        {
            return;
        }

        _currentAnimation = name;
        _currentFrame = 0;
        _frameTime = frameDuration;
        _timer = 0f;
        _isPlaying = true;
    }

    public void StopAnimation()
    {
        _isPlaying = false;
    }

    public Rectangle GetCurrentFrame()
    {
        return _animations[_currentAnimation][_currentFrame];
    }

    public void Update(GameTime gameTime)
    {
        if (!_isPlaying)
        {
            return;
        }

        _timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (_timer >= _frameTime)
        {
            _timer -= _frameTime;
            _currentFrame++;

            if (_currentFrame >= _animations[_currentAnimation].Length)
            {
                _currentFrame = 0;
            }
        }
    }

    public static Rectangle[] MakeClip(int startIndex, int frameCount, int width, int height, int textureWidth)
    {
        int framesPerRow = textureWidth / width;
        var frames = new Rectangle[frameCount];
        for (int i = 0; i < frameCount; i++)
        {
            int x = (startIndex + i) % framesPerRow * width;
            int y = (startIndex + i) / framesPerRow * height;
            frames[i] = new Rectangle(x, y, width, height);
        }
        return frames;
    }
}
Leave a Comment