use winit::{ event::{ElementState, KeyEvent, MouseButton, MouseScrollDelta, WindowEvent}, keyboard::{KeyCode, PhysicalKey}, }; use crate::camera::Camera; pub struct CameraController { speed: f32, forward: f32, cursor_start: (f32, f32), movement: (f32, f32), is_moving: bool, } impl CameraController { pub fn new(speed: f32) -> Self { Self { speed, forward: 0.0, cursor_start: (0.0, 0.0), movement: (0.0, 0.0), is_moving: false, } } pub fn process_events(&mut self, event: &WindowEvent) -> bool { match event { WindowEvent::MouseInput { state, button, .. } => { if state.is_pressed() && *button == MouseButton::Left { self.is_moving = true; return true; } else { self.is_moving = false; self.movement = (0.0, 0.0); } false } WindowEvent::CursorMoved { position, .. } => { if !self.is_moving { self.cursor_start = (position.x as f32, position.y as f32); } else { let x = -self.cursor_start.0 + position.x as f32; let x = x * 0.000001; let y = self.cursor_start.1 - position.y as f32; let y = y * 0.000001; self.movement = (x, y); } true } WindowEvent::MouseWheel { delta, .. } => match delta { MouseScrollDelta::LineDelta(_, y) => { self.forward = *y; true } _ => false, }, _ => false, } } pub fn update_camera(&mut self, camera: &mut Camera) { use cgmath::InnerSpace; let forward = camera.target - camera.eye; let forward_norm = forward.normalize(); if self.forward > 0.0 { camera.eye += forward_norm * self.speed; } else if self.forward < 0.0 { camera.eye -= forward_norm * self.speed; } if self.is_moving { camera.eye.x += self.movement.0; camera.eye.y += self.movement.1; camera.target.x += self.movement.0; camera.target.y += self.movement.1; } self.forward = 0.0; } }