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 {
fn build(&self, app: &mut App) {
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(
mut cam: Query<&mut Transform, With<Camera2d>>,
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();
if mouse_buttons.pressed(MouseButton::Left) && !mouse_buttons.just_pressed(MouseButton::Left) {
for ev in mouse_events.read() {
if let Some(delta) = ev.delta {
let mut cam = cam.single_mut();
cam.translation.x -= delta.x/window.width();
cam.translation.y += delta.y/window.height();
}
if let Some(cursor_pos) = window.cursor_position() {
if mouse_buttons.pressed(MouseButton::Left) {
let delta = cursor_pos - mouse_pos.0;
dbg!(delta);
let mut cam = cam.single_mut();
cam.translation.x -= delta.x*cam.scale.x;
cam.translation.y += delta.y*cam.scale.y;
}
mouse_pos.0 = cursor_pos;
}
}