bevy2

use bevy::prelude::*;

#[derive(Component)]
struct AnimationTimer(Timer);

#[derive(Component)]
struct AnimationIndices {
    first: usize,
    last: usize,
}

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
        .add_systems(Startup, setup)
        .add_systems(Update, animate_sprite)
        .run();
}

fn setup(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
    commands.spawn(Camera2d);

    let texture = asset_server.load("ArchDemonBasicAtk001-Sheet.png");
    

    let layout: TextureAtlasLayout = TextureAtlasLayout::from_grid(
        UVec2::new(256, 128), 
        15,              
        1,               
        None,             
        None,             
    );
    
    let texture_atlas_layout = texture_atlas_layouts.add(layout);

    // 动画索引范围 - 使用所有10帧
    let animation_indices = AnimationIndices { first: 0, last: 14 };

    // 创建实体并添加所需组件
    commands.spawn(Sprite::from_atlas_image(
        texture,
        TextureAtlas {
            layout: texture_atlas_layout,
            index: animation_indices.first,
        },
    ))
    .insert(Transform::from_scale(Vec3::splat(6.0))) // 可以调整缩放比例
    .insert(animation_indices)
    .insert(AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating))); // 可以调整动画速度
}

fn animate_sprite(
    time: Res<Time>,
    mut query: Query<(&AnimationIndices, &mut AnimationTimer, &mut Sprite)>,
) {
    for (indices, mut timer, mut sprite) in query.iter_mut() {
        timer.0.tick(time.delta());
        
        if timer.0.just_finished() {
            if let Some(atlas) = &mut sprite.texture_atlas {
                atlas.index = if atlas.index == indices.last {
                    indices.first
                } else {
                    atlas.index + 1
                };
            }
        }
    }
}