spritesheet/
spritesheet.rs

1use frug::{Color, Event, Instance, Keycode, LoadTexture, ScaleMode, Sprite, Vec2d};
2
3#[derive(PartialEq, Clone, Copy)]
4enum Animation {
5    Idle,
6    Walk,
7}
8
9fn main() {
10    let mut frug_instance = Instance::new("Spritesheet Example", 800, 600);
11    let texture_creator = frug_instance.new_texture_creator();
12    let background_color = Color::RGB(100, 100, 150);
13
14    // load the spritesheet
15    texture_creator.default_pixel_format();
16    let mut texture = match texture_creator.load_texture("examples/platformer_imgs/frog/frogo.png")
17    {
18        Ok(image) => image,
19        Err(e) => {
20            eprintln!("Failed to load texture: {}", e);
21            return;
22        }
23    };
24    texture.set_scale_mode(ScaleMode::Nearest); // to avoid blurring
25
26    let mut sprite = Sprite::new(&texture, 2, vec![6, 4], 52, 50);
27
28    let sprite_pos = Vec2d { x: 250, y: 150 };
29    let sprite_scale = Vec2d { x: 4, y: 4 };
30    let mut current_animation = Animation::Idle;
31
32    'running: loop {
33        // Input
34        for event in frug_instance.get_events() {
35            match event {
36                // Quit the application
37                Event::Quit { .. }
38                | Event::KeyDown {
39                    keycode: Some(Keycode::Escape),
40                    ..
41                } => break 'running,
42                // Change animation when pressing space
43                Event::KeyDown {
44                    keycode: Some(Keycode::Space),
45                    ..
46                } => {
47                    if current_animation == Animation::Idle {
48                        current_animation = Animation::Walk;
49                    } else {
50                        current_animation = Animation::Idle;
51                    }
52                    let animation_u32 = current_animation.clone() as u32;
53                    sprite.start_animation(&animation_u32);
54                }
55                _ => {}
56            }
57        }
58
59        // Update
60        sprite.update();
61
62        // Render
63        frug_instance.clear(background_color);
64        frug_instance.draw_sprite(&sprite, &sprite_pos, &sprite_scale);
65        frug_instance.present();
66
67        std::thread::sleep(std::time::Duration::from_millis(100));
68    }
69}