use bevy::app::{App, Plugin, Update};
use bevy::math::Vec2;
use bevy::prelude::{Component, Query, Transform, With};
pub trait ColliderTrait{}
#[derive(Component)]
pub struct RectangleCollider{pub half_x: f32, pub half_y: f32, pub position: Vec2}
impl RectangleCollider{
pub fn new(half_x: f32, half_y: f32) -> Self {
Self{half_x, half_y, position: Vec2::ZERO}
}
pub fn check_collision(self, other: &Self) -> bool {
if other.position.x > self.position.x {
let distance_x = other.position.x - self.position.x;
let mut distance_y;
if other.position.y > self.position.y {
distance_y = other.position.y - self.position.y;
} else {
distance_y = self.position.y - other.position.y;
}
if distance_x < self.half_x + other.half_x {
if distance_y < self.half_y + other.half_y {
return true
} else {
return false
}
} else {
return false
}
} else if other.position.x < self.position.x {
let distance_x = self.position.x - other.position.x;
let mut distance_y;
if other.position.y > self.position.y {
distance_y = other.position.y - self.position.y;
} else {
distance_y = self.position.y - other.position.y;
}
if distance_x < self.half_x + other.half_x {
if distance_y < self.half_y + other.half_y {
return true
} else {
return false
}
} else {
return false
}
}
let mut distance_y;
if other.position.y > self.position.y {
distance_y = other.position.y - self.position.y;
} else {
distance_y = self.position.y - other.position.y;
}
if distance_y < self.half_y + other.half_y {
true
} else {
false
}
}
}
impl ColliderTrait for RectangleCollider {}
impl Clone for RectangleCollider {
fn clone(&self) -> Self {
RectangleCollider{half_x:self.half_x, half_y:self.half_y, position:self.position}
}
}
pub struct CollisionPlugin;
impl Plugin for CollisionPlugin {
fn build(&self, app: &mut App) {
fn update_collider_pos(mut collider_query: Query<(&mut RectangleCollider, &mut Transform), With<RectangleCollider>>) {
for (mut collider_collider, mut transform) in collider_query.iter_mut() {
collider_collider.position = transform.translation.truncate();
}
}
app.add_systems(Update, update_collider_pos);
}
}