moving_rect/
moving_rect.rs

1use std::error::Error;
2
3use simple_game_engine::{self as sge, prelude::*};
4
5const MOVEMENT_SPEED: f64 = 200.0;
6const SCREEN_WIDTH: u32 = 480;
7const SCREEN_HEIGHT: u32 = 360;
8const RECT_SIZE: u32 = 100;
9
10struct App {
11    x: f64,
12    y: f64,
13}
14
15impl App {
16    pub fn new() -> Self {
17        Self { x: 10.0, y: 10.0 }
18    }
19}
20
21impl sge::Application for App {
22    fn on_update(
23        &mut self,
24        canvas: &mut WindowCanvas,
25        input: &InputState,
26        elapsed_time: f64,
27    ) -> sge::ApplicationResult {
28        // Move the rectangle with the keyboard
29        if input.keyboard.held(Scancode::Up) {
30            self.y = (self.y - MOVEMENT_SPEED * elapsed_time).max(0.0);
31        } else if input.keyboard.held(Scancode::Down) {
32            self.y =
33                (self.y + MOVEMENT_SPEED * elapsed_time).min((SCREEN_HEIGHT - RECT_SIZE) as f64);
34        }
35        if input.keyboard.held(Scancode::Left) {
36            self.x = (self.x - MOVEMENT_SPEED * elapsed_time).max(0.0);
37        } else if input.keyboard.held(Scancode::Right) {
38            self.x =
39                (self.x + MOVEMENT_SPEED * elapsed_time).min((SCREEN_WIDTH - RECT_SIZE) as f64);
40        }
41        // Move the rectangle with the mouse
42        if input.mouse.buttons.held(MouseButton::Left) {
43            self.x = input.mouse.x as f64;
44            self.y = input.mouse.y as f64;
45        }
46        // Fill the screen
47        canvas.set_draw_color(Color::BLACK);
48        canvas.clear();
49        canvas.set_draw_color(Color::GRAY);
50        canvas.fill_rect(Rect::new(
51            self.x as i32,
52            self.y as i32,
53            RECT_SIZE,
54            RECT_SIZE,
55        ))?;
56        Ok(true)
57    }
58}
59
60fn main() -> Result<(), Box<dyn Error>> {
61    let mut app = App::new();
62    let mut engine = sge::Engine::new(&mut app, "Test App", SCREEN_WIDTH, SCREEN_HEIGHT)?;
63    engine.start(false)
64}