#[derive(Debug, Clone, Copy)]
pub struct Physics {
pub velocity: (f32, f32),
pub acceleration: (f32, f32),
pub drag: f32, pub gravity_scale: f32, }
impl Physics {
pub fn new() -> Self {
Self {
velocity: (0.0, 0.0),
acceleration: (0.0, 0.0),
drag: 0.0,
gravity_scale: 0.0,
}
}
pub fn with_velocity(mut self, vx: f32, vy: f32) -> Self {
self.velocity = (vx, vy);
self
}
pub fn with_gravity(mut self, scale: f32) -> Self {
self.gravity_scale = scale;
self
}
pub fn with_drag(mut self, drag: f32) -> Self {
self.drag = drag.clamp(0.0, 1.0);
self
}
pub fn apply_force(&mut self, fx: f32, fy: f32) {
self.acceleration.0 += fx;
self.acceleration.1 += fy;
}
pub fn update(&mut self, dt: f32, gravity: f32) {
self.acceleration.1 += gravity * self.gravity_scale;
self.velocity.0 += self.acceleration.0 * dt;
self.velocity.1 += self.acceleration.1 * dt;
if self.drag > 0.0 {
let drag_factor = 1.0 - self.drag * dt;
self.velocity.0 *= drag_factor.max(0.0);
self.velocity.1 *= drag_factor.max(0.0);
}
self.acceleration = (0.0, 0.0);
}
pub fn get_displacement(&self, dt: f32) -> (f32, f32) {
(self.velocity.0 * dt, self.velocity.1 * dt)
}
}
impl Default for Physics {
fn default() -> Self {
Self::new()
}
}