Search code examples
rustgame-developmentbevy

Is there a way of detecting collision of Sprites in the bevy game engine?


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.


Solution

  • 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;
            }
        }
    }