Bevy: How to get the coordinates of a mouse click?

Created on 23 Aug 2020  路  4Comments  路  Source: bevyengine/bevy

Hi, I've checked through the docs and the source code and I cannot seem to figure out how I would get the x & y coordinates of a mouse click. Is it currently possible to do this with bevy?

input question

Most helpful comment

Hmm, so you just keep track of the latest mouse movement, and then read that state when you get a click event. That does seem like a bit of unnecessary friction, perhaps this issue can stay open as a tracker on making this a bit simpler.

All 4 comments

This is porbably not the best way, but this is my system witch track the mouse position and in game position (if you are using a Camera2dComponents) :


fn build(&self, app: &mut AppBuilder) {
        app
             .init_resource::<CursorState>()
            .add_system(update_cursor_state_system.system())

#[derive(Default)]
struct CursorState {
    cursor_moved_event_reader: EventReader<CursorMoved>,
    mouse_wheel_event_reader: EventReader<MouseWheel>,
    cursor_position: Vec2,
    cursor_position_in_world: Vec2,
}

fn update_cursor_state_system(
    mut state: ResMut<CursorState>,
    windows: Res<Windows>,
    cursor_moved_events: Res<Events<CursorMoved>>,
    mut query: Query<(&Camera, &Camera2D, &Translation, &Scale)>,
) {
    if let Some(cursor_moved) = state.cursor_moved_event_reader.latest(&cursor_moved_events) {
        state.cursor_position = cursor_moved.position;
    }
    if let Some(window) = windows.get_primary() {
        for (_camera_2d, _, translation, scale) in &mut query.iter() {
            let cursor_x = translation.0.x()
                + (state.cursor_position[0] - (window.width as f32 * 0.5)) * scale.0;
            let cursor_y = translation.0.y()
                + (state.cursor_position[1] - (window.height as f32 * 0.5)) * scale.0;
            state.cursor_position_in_world = [cursor_x, cursor_y].into();
        }
    }
}

I would love to have a world to mouse function and mouse to world function integrated into bevy :P

Hmm, so you just keep track of the latest mouse movement, and then read that state when you get a click event. That does seem like a bit of unnecessary friction, perhaps this issue can stay open as a tracker on making this a bit simpler.

@ahfuckme
Thanks a lot for raising these kind of issues. It's important for bevy to know where people encounter friction in their experience and it helps us prioritize work. Would you be ok with continuing that specific discussion on https://stackoverflow.com/questions/63541917/reading-the-position-of-a-mouse-click-in-bevy . We could close this current issue and raise a different one thats focused on improving the experience and creating the upcoming axis api that will make that kind of work simpler in the future.

Works for me!

Was this page helpful?
0 / 5 - 0 ratings