Skip to main content

simple_animation/
simple_animation.rs

1//! This example is a show off about the animation system of the engine.
2//! Our entity have a static sprite component and a animation component.
3//! The animation component doesn't have any dependency on other components.
4//! The animation component store N sprite sheets, with a title as the key.
5//! In this example, a looped animation can be controlled by the keyboard keys.
6
7use lotus_engine::*;
8
9your_game!(
10    WindowConfiguration::default().title("Simple Animation".to_string()),
11    setup,
12    update
13);
14
15fn setup(context: &mut Context) {
16    let dummy: Sprite = Sprite::new("textures/lotus_pink_128x128.png".to_string());
17    let scarfy_sprite_sheet: SpriteSheet = SpriteSheet::new(
18        "textures/animations/scarfy.png".to_string(),
19        LoopingState::Once,
20        (124.0, 124.0),
21        0.5,
22        1,
23        6,
24        vec![0, 1, 2, 3, 4, 5]
25    );
26
27    let mut animation: Animation = Animation::default();
28    animation.add_sprite_sheet("run".to_string(), scarfy_sprite_sheet);
29    context.commands.spawn(vec![Box::new(dummy), Box::new(animation)]);
30}
31
32fn update(context: &mut Context) {
33    let keyboard_input: ResourceRefMut<'_, KeyboardInput> = context.world.get_resource_mut::<KeyboardInput>().unwrap();
34    let mut query: Query = Query::new(&context.world).with::<Animation>();
35    let result: Entity = query.entities_with_components().unwrap().first().unwrap().clone();
36    let mut animation: ComponentRefMut<'_, Animation> = context.world.get_entity_component_mut::<Animation>(&result).unwrap();
37
38    if keyboard_input.is_key_pressed(KeyboardKey::KeyW) {
39        animation.play("run".to_string());
40    } else if keyboard_input.is_key_pressed(KeyboardKey::KeyA) {
41        animation.pause("run".to_string());
42    } else if keyboard_input.is_key_pressed(KeyboardKey::KeyS) {
43        animation.resume("run".to_string());
44    } else if keyboard_input.is_key_pressed(KeyboardKey::KeyD) {
45        animation.stop("run".to_string());
46    }
47}