zoomie/src/controller.rs

62 lines
1.3 KiB
Rust
Raw Normal View History

use winit::{
event::{ElementState, KeyEvent, MouseScrollDelta, WindowEvent},
keyboard::{KeyCode, PhysicalKey},
};
use crate::camera::Camera;
pub struct CameraController {
speed: f32,
cursor: (f64, f64),
forward: f32,
}
impl CameraController {
pub fn new(speed: f32) -> Self {
Self {
speed,
cursor: (0.0, 0.0),
forward: 0.0,
}
}
pub fn process_events(&mut self, event: &WindowEvent) -> bool {
match event {
WindowEvent::CursorMoved { position, .. } => {
self.cursor = (position.x, position.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;
}
camera.eye.x = (self.cursor.0 as f32 / 1920.0) - 0.5;
camera.eye.y = (-self.cursor.1 as f32 / 1080.0) + 0.5;
camera.target.x = (self.cursor.0 as f32 / 1920.0) - 0.5;
camera.target.y = (-self.cursor.1 as f32 / 1080.0) + 0.5;
self.forward = 0.0;
}
}