-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhuman_input.rs
68 lines (60 loc) · 2.05 KB
/
human_input.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
use crate::{core_logic::*, *};
pub struct HumanInputPlugin;
impl Plugin for HumanInputPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, (move_unit, select_unit));
}
}
fn find_pointer_position(
camera_query: Query<(&Camera, &GlobalTransform)>,
windows: Query<&Window>,
) -> Option<Vec2> {
let (camera, camera_transform) = camera_query.iter().next()?;
let cursor_position = windows.single().cursor_position()?;
camera.viewport_to_world_2d(camera_transform, cursor_position)
}
fn move_unit(
camera_query: Query<(&Camera, &GlobalTransform)>,
windows: Query<&Window>,
clicks: Res<Input<MouseButton>>,
mut events: EventWriter<MoveToCommand>,
entities: Query<Entity, With<Selected>>,
) {
if clicks.just_pressed(MouseButton::Right) {
let Some(point) = find_pointer_position(camera_query, windows) else {
return;
};
if let Some(entity) = entities.iter().next() {
events.send(MoveToCommand {
target: entity,
destination: point,
})
}
}
}
fn select_unit(
camera_query: Query<(&Camera, &GlobalTransform)>,
windows: Query<&Window>,
clicks: Res<Input<MouseButton>>,
entities: Query<(&Transform, Entity), With<Speed>>,
mut selections: EventWriter<SelectEvent>,
mut unselections: EventWriter<UnselectEvent>,
) {
let Some(point) = find_pointer_position(camera_query, windows) else {
return;
};
if clicks.pressed(MouseButton::Left) {
let mut any_clicked = false;
for (transform, entity) in entities.iter() {
let bl = transform.translation.to_vec2() - transform.scale.to_vec2() / 2.0;
let tr = transform.translation.to_vec2() + transform.scale.to_vec2() / 2.0;
if bl.x < point.x && point.x < tr.x && bl.y < point.y && point.y < tr.y {
selections.send(entity.into());
any_clicked = true;
}
}
if !any_clicked {
unselections.send(UnselectEvent::All);
}
}
}