use bevy::prelude::*;
pub struct CursorPlugin;
impl Plugin for CursorPlugin {
fn build(&self, app: &mut App) {
app .register_type::<Cursor>()
.init_resource::<Cursor>()
.add_systems(First, update_cursor);
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Resource, Default, Reflect)]
#[reflect(Resource)]
pub struct Cursor {
position: Vec2,
last_position: Vec2,
}
impl Cursor {
pub fn set(&mut self, position: Vec2) {
self.last_position = self.position;
self.position = position;
}
pub fn offset(&mut self, offset: Vec2) {
self.set(self.position + offset);
}
pub fn position(&self) -> Vec2 {
self.position
}
}
#[allow(clippy::needless_pass_by_value)]
fn update_cursor(mut cursor: ResMut<Cursor>, windows: Query<&Window>) {
for window in &windows {
if let Some(mouse) = window.cursor_position() {
if mouse != cursor.last_position {
cursor.set(mouse);
}
}
}
}