#[derive(Debug, Clone, Copy)]
pub struct Camera {
pub x: f32,
pub y: f32,
pub zoom: f32,
pub viewport_width: u32,
pub viewport_height: u32,
}
impl Camera {
pub fn new(viewport_width: u32, viewport_height: u32) -> Self {
Self {
x: 0.0,
y: 0.0,
zoom: 1.0,
viewport_width,
viewport_height,
}
}
pub fn world_to_screen(&self, world_x: f32, world_y: f32) -> (i32, i32) {
let screen_x = ((world_x - self.x) * self.zoom) as i32;
let screen_y = ((world_y - self.y) * self.zoom) as i32;
(screen_x, screen_y)
}
pub fn screen_to_world(&self, screen_x: i32, screen_y: i32) -> (f32, f32) {
let world_x = (screen_x as f32 / self.zoom) + self.x;
let world_y = (screen_y as f32 / self.zoom) + self.y;
(world_x, world_y)
}
pub fn follow(&mut self, target_x: f32, target_y: f32, smoothness: f32, dt: f32) {
let center_x = target_x - (self.viewport_width as f32 / (2.0 * self.zoom));
let center_y = target_y - (self.viewport_height as f32 / (2.0 * self.zoom));
let lerp_factor = (smoothness * dt).min(1.0);
self.x += (center_x - self.x) * lerp_factor;
self.y += (center_y - self.y) * lerp_factor;
}
pub fn center_on(&mut self, x: f32, y: f32) {
self.x = x - (self.viewport_width as f32 / (2.0 * self.zoom));
self.y = y - (self.viewport_height as f32 / (2.0 * self.zoom));
}
pub fn set_zoom(&mut self, zoom: f32) {
self.zoom = zoom.max(0.1);
}
pub fn resize_viewport(&mut self, width: u32, height: u32) {
self.viewport_width = width;
self.viewport_height = height;
}
}