cam move with mouse

This commit is contained in:
Arkitu 2024-12-24 09:45:10 +01:00
parent d3e710dc71
commit 3ea4fda9c5

View File

@ -4,7 +4,8 @@ pub struct Plugin;
impl bevy::prelude::Plugin for Plugin { impl bevy::prelude::Plugin for Plugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems(Startup, setup) app.add_systems(Startup, setup)
.add_systems(Update, move_cam); .add_systems(Update, move_cam)
.init_resource::<MousePos>();
} }
} }
@ -16,20 +17,24 @@ fn setup(mut cmds: Commands, window: Query<&Window>) {
)); ));
} }
#[derive(Resource, Default)]
struct MousePos(Vec2);
fn move_cam( fn move_cam(
mut cam: Query<&mut Transform, With<Camera2d>>, mut cam: Query<&mut Transform, With<Camera2d>>,
mouse_buttons: Res<ButtonInput<MouseButton>>, mouse_buttons: Res<ButtonInput<MouseButton>>,
mut mouse_events: EventReader<CursorMoved>, window: Query<&Window, With<PrimaryWindow>>,
window: Query<&Window, With<PrimaryWindow>> mut mouse_pos: ResMut<MousePos>
) { ) {
let window = window.single(); let window = window.single();
if mouse_buttons.pressed(MouseButton::Left) && !mouse_buttons.just_pressed(MouseButton::Left) { if let Some(cursor_pos) = window.cursor_position() {
for ev in mouse_events.read() { if mouse_buttons.pressed(MouseButton::Left) {
if let Some(delta) = ev.delta { let delta = cursor_pos - mouse_pos.0;
let mut cam = cam.single_mut(); dbg!(delta);
cam.translation.x -= delta.x/window.width(); let mut cam = cam.single_mut();
cam.translation.y += delta.y/window.height(); cam.translation.x -= delta.x*cam.scale.x;
} cam.translation.y += delta.y*cam.scale.y;
} }
mouse_pos.0 = cursor_pos;
} }
} }