Simple collisions
This commit is contained in:
parent
52c98da1fd
commit
03b59593b7
3 changed files with 58 additions and 1 deletions
21
src/collision/collider.rs
Normal file
21
src/collision/collider.rs
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
use bevy::{math::FloatPow, prelude::*};
|
||||||
|
|
||||||
|
/// Two-dimensional collider that detects collisions with another colliders
|
||||||
|
///
|
||||||
|
/// Composite colliders are not yet supported
|
||||||
|
#[derive(Component)]
|
||||||
|
#[require(Transform)]
|
||||||
|
pub enum Collider {
|
||||||
|
Circle(f32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Collider {
|
||||||
|
/// Function that checks collision between two colliders
|
||||||
|
///
|
||||||
|
/// Algorithm is specific for each collider type
|
||||||
|
pub fn detect_collision(&self, self_center: Vec2, other: &Self, other_center: Vec2) -> bool {
|
||||||
|
match (self, other) {
|
||||||
|
(Collider::Circle(self_radius), Collider::Circle(other_radius)) => {(other_center-self_center).length_squared() <= (self_radius+other_radius).squared()}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
8
src/collision/event.rs
Normal file
8
src/collision/event.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
/// Event that triggers every frame collision occurs
|
||||||
|
#[derive(EntityEvent)]
|
||||||
|
pub struct Collided {
|
||||||
|
pub entity: Entity,
|
||||||
|
pub with: Entity,
|
||||||
|
}
|
||||||
|
|
@ -1,9 +1,37 @@
|
||||||
use bevy::prelude::*;
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
use collider::Collider;
|
||||||
|
use event::Collided;
|
||||||
|
|
||||||
|
mod collider;
|
||||||
|
mod event;
|
||||||
|
|
||||||
pub struct CollisionPlugin;
|
pub struct CollisionPlugin;
|
||||||
|
|
||||||
impl Plugin for CollisionPlugin {
|
impl Plugin for CollisionPlugin {
|
||||||
fn build(&self, app: &mut App) {
|
fn build(&self, app: &mut App) {
|
||||||
//todo!()
|
app.add_systems(Update, detect_collision_system);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn detect_collision_system(mut commands: Commands, query: Query<(Entity, &Transform, &Collider)>) {
|
||||||
|
for (first_entity, first_transform, first_collider) in query {
|
||||||
|
for (second_entity, second_transform, second_collider) in query {
|
||||||
|
if first_entity == second_entity {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if first_collider.detect_collision(
|
||||||
|
first_transform.translation.truncate(),
|
||||||
|
&second_collider,
|
||||||
|
second_transform.translation.truncate()
|
||||||
|
){
|
||||||
|
commands.trigger(
|
||||||
|
Collided {
|
||||||
|
entity:first_entity,
|
||||||
|
with:second_entity
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue