Skip to main content

2d_platformer_simple/
2d_platformer_simple.rs

1use sge::prelude::*;
2
3const PLAYER_RADIUS: f32 = 30.0;
4
5#[main("2D Platformer")]
6fn main() -> anyhow::Result<()> {
7    let mut world = PhysicsWorld::new();
8
9    let mut player = world
10        .create_player_controller(Bounds::Circle(PLAYER_RADIUS))
11        .with_position(Vec2::new(0.0, -200.0));
12
13    player
14        .set_binds()
15        .jump(KeyCode::Space)
16        .right(KeyCode::KeyF)
17        .left(KeyCode::KeyS);
18
19    player.set_move_speed(5.0);
20    player.set_double_jumps(1);
21    player.set_jump_velocity(13.0);
22    world.set_gravity(50.0);
23
24    let platforms = vec![
25        platform(-500.0, 400.0, 1000.0),
26        platform(-400.0, 250.0, 200.0),
27        platform(200.0, 250.0, 200.0),
28        platform(-100.0, 100.0, 200.0),
29    ];
30
31    for p in &platforms {
32        world
33            .create_fixed(Bounds::Rect(p.size))
34            .with_position(p.center());
35    }
36
37    loop {
38        clear_screen(Color::NEUTRAL_900);
39
40        if key_pressed(KeyCode::KeyR) {
41            player.set_position(Vec2::new(0.0, -200.0));
42        }
43
44        if player.position().y > 1000.0 {
45            player.add_impulse(Vec2::Y * 15.0);
46        }
47
48        draw_circle_world(player.position(), PLAYER_RADIUS, Color::RED_500);
49
50        for platform in &platforms {
51            draw_world(platform);
52        }
53
54        world.update();
55
56        if should_quit() {
57            break;
58        }
59
60        next_frame().await;
61    }
62
63    Ok(())
64}
65
66fn platform(x: f32, y: f32, w: f32) -> Rect {
67    Rect::new(Vec2::new(x, y), Vec2::new(w, 20.0), Color::NEUTRAL_800)
68}