-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun world
91 lines (79 loc) · 2.38 KB
/
run world
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
[dependencies]
ggez = "0.5"
use ggez::event;
use ggez::graphics::{self, Color, DrawMode, DrawParam, Rect};
use ggez::{Context, GameResult};
use ggez::input::keyboard::{self, KeyCode};
use ggez::nalgebra as na;
const SCREEN_WIDTH: f32 = 800.0;
const SCREEN_HEIGHT: f32 = 600.0;
const GRAVITY: f32 = 0.5;
const JUMP_VELOCITY: f32 = -10.0;
struct Player {
position: na::Point2<f32>,
velocity: na::Vector2<f32>,
is_jumping: bool,
}
impl Player {
fn new() -> Player {
Player {
position: na::Point2::new(50.0, SCREEN_HEIGHT - 50.0),
velocity: na::Vector2::new(0.0, 0.0),
is_jumping: false,
}
}
fn jump(&mut self) {
if !self.is_jumping {
self.velocity.y = JUMP_VELOCITY;
self.is_jumping = true;
}
}
fn update(&mut self) {
self.velocity.y += GRAVITY;
self.position += self.velocity;
if self.position.y > SCREEN_HEIGHT - 50.0 {
self.position.y = SCREEN_HEIGHT - 50.0;
self.velocity.y = 0.0;
self.is_jumping = false;
}
}
fn draw(&self, ctx: &mut Context) -> GameResult {
let rect = Rect::new(self.position.x, self.position.y, 50.0, 50.0);
graphics::draw(ctx, &rect, DrawParam::default().color(Color::WHITE))
}
}
struct GameState {
player: Player,
}
impl GameState {
fn new() -> GameState {
GameState {
player: Player::new(),
}
}
}
impl event::EventHandler for GameState {
fn update(&mut self, _ctx: &mut Context) -> GameResult {
self.player.update();
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult {
graphics::clear(ctx, Color::BLACK);
self.player.draw(ctx)?;
graphics::present(ctx)
}
fn key_down_event(&mut self, _ctx: &mut Context, keycode: KeyCode, _keymods: keyboard::KeyMods, _repeat: bool) {
match keycode {
KeyCode::Space => self.player.jump(),
_ => (),
}
}
}
fn main() -> GameResult {
let mut cb = ggez::ContextBuilder::new("running_game", "ggez");
cb.window_setup(ggez::conf::WindowSetup::default().title("Running Game"));
cb.window_mode(ggez::conf::WindowMode::default().dimensions(SCREEN_WIDTH, SCREEN_HEIGHT));
let (ctx, event_loop) = &mut cb.build()?;
let state = &mut GameState::new();
event::run(ctx, event_loop, state)
}