Skip to content

Latest commit

 

History

History
89 lines (72 loc) · 3.09 KB

mouse_events.md

File metadata and controls

89 lines (72 loc) · 3.09 KB

Mouse Events

To capture other mouse information, we can use EventReader. For example, we can use EventReader<CursorMoved> to monitor the mouse position on the window.

In the following example, we create a Circle that follows the mouse pointer.

fn handle_keys(
    mut events: EventReader<CursorMoved>,
    mut circles: Query<&mut Transform, With<Handle<ColorMaterial>>>,
) {
    let mut transform = circles.single_mut();

    for event in events.read() {
        *transform = Transform::from_xyz(
            event.position.x - 1280. / 2.,
            -event.position.y + 720. / 2.,
            0.,
        );
    }
}

The code event.position.x - 1280. / 2. and -event.position.y + 720. / 2. converts the mouse x and y positions to the space of Camera. This is done by assuming the window has size 1280 x 720.

The full code is as follows:

use bevy::{
    app::{App, Startup, Update},
    asset::{Assets, Handle},
    core_pipeline::core_2d::Camera2dBundle,
    ecs::{
        event::EventReader,
        query::With,
        system::{Commands, Query, ResMut},
    },
    render::mesh::{shape::Circle, Mesh},
    sprite::{ColorMaterial, ColorMesh2dBundle},
    transform::components::Transform,
    utils::default,
    window::CursorMoved,
    DefaultPlugins,
};

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, handle_keys)
        .run();
}

fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
    commands.spawn(Camera2dBundle::default());

    commands.spawn(ColorMesh2dBundle {
        mesh: meshes.add(Circle::new(50.).into()).into(),
        ..default()
    });
}

fn handle_keys(
    mut events: EventReader<CursorMoved>,
    mut circles: Query<&mut Transform, With<Handle<ColorMaterial>>>,
) {
    let mut transform = circles.single_mut();

    for event in events.read() {
        *transform = Transform::from_xyz(
            event.position.x - 1280. / 2.,
            -event.position.y + 720. / 2.,
            0.,
        );
    }
}

Result:

Mouse Events

In addition to CursorMoved, there are other mouse-related Events that we can use along with EventReader such as MouseButtonInput, MouseMotion, MouseWheel, etc.

➡️ Next: Mouse Icon

📘 Back: Table of contents