6

Currently im using the Position of two objects (comets and the ship) to detect if they collide.

fn collision_detection(
    comets: Query<&Transform, With<Comet>>,
    mut ships: Query<(&Transform, &mut ShipStatus), With<Ship>>,
) {
    for comet in comets.iter() {
        for (ship, mut status) in ships.iter_mut() {
            if comet.translation.x < ship.translation.x + 80.0 && comet.translation.y < ship.translation.y + 80.0
            && comet.translation.x > ship.translation.x - 80.0 && comet.translation.y > ship.translation.y - 80.0 {
                status.dead = true;
            }
        }
    }
}

But there has to be a better way of doing this.

Bruno Wallner
  • 383
  • 5
  • 13

1 Answers1

6

Bevy doesn't have a complete collision system currently. Unless it has been expanded in the few months since the introductory page was created:

Physics

Many games require collision detection and physics. I'm planning on building a plug-able physics interface with nphysics / ncollide as the first backend.

Fortunately, this simple example is actually provided by bevy::sprite::collide_aabb::collide which does simple AABB collision detection.

use bevy::sprite::collide_aabb::collide;

let ship_size = Vec2::new(80.0, 80.0);
let comet_size = Vec2::new(0.0, 0.0);
for comet in comets.iter() {
    for (ship, mut status) in ships.iter_mut() {
        if collide(ship.translation, ship_size, comet.translation, comet_size).is_some() {
            status.dead = true;
        }
    }
}
kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • 1
    Hi, cool answer! Is there a faster approach? currently it seems this should work in O(n*m), while there are data structures that allow faster collision detection, such as [R-trees](https://en.wikipedia.org/wiki/R-tree) and the other structures derived from it. However, I struggle to see how this would be implemented in a bevy `system` that gets a simple iterator over the ships and comets... – nir shahar Oct 11 '22 at 10:41