-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
keyboard.rs
77 lines (64 loc) 路 1.93 KB
/
keyboard.rs
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
use tetra::graphics::{self, Color, DrawParams, Texture};
use tetra::input::{self, Key};
use tetra::math::Vec2;
use tetra::{Context, ContextBuilder, State};
struct GameState {
texture: Texture,
position: Vec2<f32>,
}
impl GameState {
fn new(ctx: &mut Context) -> tetra::Result<GameState> {
Ok(GameState {
texture: Texture::new(ctx, "./examples/resources/player.png")?,
position: Vec2::new(32.0, 32.0),
})
}
}
impl State for GameState {
fn update(&mut self, ctx: &mut Context) -> tetra::Result {
if input::is_key_down(ctx, Key::A) {
self.position.x -= 4.0;
}
if input::is_key_down(ctx, Key::D) {
self.position.x += 4.0;
}
if input::is_key_down(ctx, Key::W) {
self.position.y -= 4.0;
}
if input::is_key_down(ctx, Key::S) {
self.position.y += 4.0;
}
let mut pressed = input::get_keys_pressed(ctx).peekable();
if pressed.peek().is_some() {
println!(
"Keys pressed this update: {:?}",
pressed.collect::<Vec<_>>()
);
}
let mut released = input::get_keys_released(ctx).peekable();
if released.peek().is_some() {
println!(
"Keys released this update: {:?}",
released.collect::<Vec<_>>()
);
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> tetra::Result {
graphics::clear(ctx, Color::rgb(0.769, 0.812, 0.631));
self.texture.draw(
ctx,
DrawParams::new()
.position(self.position)
.origin(Vec2::new(8.0, 8.0))
.scale(Vec2::new(2.0, 2.0)),
);
Ok(())
}
}
fn main() -> tetra::Result {
ContextBuilder::new("Keyboard Input", 640, 480)
.quit_on_escape(true)
.build()?
.run(GameState::new)
}