use crate::animation::Animation;
use crate::collision::Collider;
use crate::physics::Physics;
use crate::sprite::SpriteSheet;
use crate::transform::Transform;
use std::collections::HashMap;
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub enum PlayerAction {
Idle,
Walk,
Attack,
}
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub enum Direction {
Down,
Up,
Left,
Right,
}
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum ObjectType {
Player,
Coin,
Enemy,
}
pub struct GameObject {
pub object_type: ObjectType,
pub transform: Transform,
pub z_index: i32, pub active: bool,
pub physics: Option<Physics>,
pub collider: Option<Collider>,
pub sheets: HashMap<PlayerAction, SpriteSheet>,
pub animations: HashMap<Direction, Animation>,
pub current_action: PlayerAction,
pub facing_direction: Direction,
}
impl GameObject {
pub fn new(x: f32, y: f32, object_type: ObjectType) -> Self {
Self {
object_type,
transform: Transform::new(x, y),
z_index: 0,
active: true,
physics: None,
collider: None,
sheets: HashMap::new(),
animations: HashMap::new(),
current_action: PlayerAction::Idle,
facing_direction: Direction::Down,
}
}
pub fn with_physics(mut self, physics: Physics) -> Self {
self.physics = Some(physics);
self
}
pub fn with_collider(mut self, collider: Collider) -> Self {
self.collider = Some(collider);
self
}
pub fn with_z_index(mut self, z_index: i32) -> Self {
self.z_index = z_index;
self
}
pub fn update_physics(&mut self, dt: f32, gravity: f32) {
if let Some(physics) = &mut self.physics {
physics.update(dt, gravity);
let (dx, dy) = physics.get_displacement(dt);
self.transform.translate(dx, dy);
}
}
pub fn update_animation(&mut self, dt: f32) {
if let Some(animation) = self.animations.get_mut(&self.facing_direction) {
if self.current_action == PlayerAction::Walk {
animation.update(dt);
} else {
animation.current_relative_frame = 0;
}
}
}
pub fn get_collision_rect(&self) -> Option<crate::collision::Rect> {
self.collider.as_ref().map(|collider| {
collider.get_rect(self.transform.position.0, self.transform.position.1)
})
}
}