-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathecs.rs
More file actions
114 lines (91 loc) · 2.98 KB
/
ecs.rs
File metadata and controls
114 lines (91 loc) · 2.98 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use peacock::ecs::{self, Component, Entity};
use peacock::graphics::{self, DrawImageParams, Image, Rectangle};
use peacock::input::{self, Key};
use peacock::Result;
use peacock::{ContextBuilder, State, Vector2f};
type Context = peacock::Context<()>;
#[derive(Debug)]
struct Transform {
pub position: Vector2f,
}
impl Component for Transform {}
#[derive(Debug)]
struct StaticSprite {
pub source: Rectangle<i32>,
}
impl Component for StaticSprite {}
struct EcsExample {
sprite_sheet: Image,
player: Entity,
}
impl EcsExample {
fn new(ctx: &mut Context) -> Result<Self> {
let sprite_sheet = Image::from_file(ctx, "examples/res/0x72_dungeon_ii.png")?;
let player = ecs::create_entity(ctx)
.with(Transform {
position: Vector2f::new(0.0, 0.0),
})
.with(StaticSprite {
source: Rectangle::<i32>::new(128, 76, 15, 20),
})
.build();
Ok(Self {
sprite_sheet,
player,
})
}
}
impl State for EcsExample {
type Context = ();
fn update(&mut self, ctx: &mut Context) -> Result<()> {
let direction = {
let mut direction = Vector2f::ZERO;
if input::is_key_down(ctx, Key::A) {
direction += -Vector2f::UNIT_X
}
if input::is_key_down(ctx, Key::D) {
direction += Vector2f::UNIT_X;
}
if input::is_key_down(ctx, Key::W) {
direction += -Vector2f::UNIT_Y;
}
if input::is_key_down(ctx, Key::S) {
direction += Vector2f::UNIT_Y;
}
if direction == Vector2f::ZERO {
direction
} else {
direction.normalize()
}
};
if let Some(transform) = ecs::get_component_mut::<_, Transform>(ctx, self.player) {
let speed = 10.0;
transform.position += direction * speed;
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context, _dt: f64) -> Result<()> {
for entity in ecs::entities(ctx) {
let transform = ecs::get_component::<_, Transform>(ctx, entity);
let static_sprite = ecs::get_component::<_, StaticSprite>(ctx, entity);
match (transform, static_sprite) {
(Some(transform), Some(static_sprite)) => {
let draw_params = DrawImageParams {
position: transform.position,
clip_rect: Some(static_sprite.source),
scale: Some(Vector2f::new(8.0, 8.0)),
..Default::default()
};
graphics::draw(ctx, &self.sprite_sheet, &draw_params)?;
}
_ => {}
};
}
Ok(())
}
}
fn main() -> Result<()> {
ContextBuilder::new("Entity Component System", 1920, 1080)
.build_empty()?
.run_with_result(EcsExample::new)
}