Skip to main content

traaains/game/
cursor.rs

1use bevy::{
2    app::{App, Plugin, Update},
3    camera::Camera,
4    ecs::{
5        resource::Resource,
6        system::{Query, ResMut},
7    },
8    math::Vec2,
9    transform::components::GlobalTransform,
10    window::Window,
11};
12
13pub fn cursor_world_pos(
14    window: Query<&Window>,
15    camera: Query<(&Camera, &GlobalTransform)>,
16) -> Option<Vec2> {
17    let (camera, camera_transform) = camera.single().ok()?;
18
19    camera
20        .viewport_to_world_2d(
21            camera_transform,
22            window.single().unwrap().cursor_position()?,
23        )
24        .ok()
25}
26
27#[derive(Default, Resource)]
28pub struct CursorPos(pub Vec2);
29
30fn update_cursor_pos(
31    window: Query<&Window>,
32    camera: Query<(&Camera, &GlobalTransform)>,
33    mut cursor_pos: ResMut<CursorPos>,
34) {
35    cursor_pos.0 = cursor_world_pos(window, camera).unwrap_or_default();
36}
37
38/// Manages resource tracking the current cursor position
39pub struct CursorPlugin;
40
41impl Plugin for CursorPlugin {
42    fn build(&self, app: &mut App) {
43        app.insert_resource(CursorPos::default())
44            .add_systems(Update, update_cursor_pos);
45    }
46}