dimforge / rapier

2D and 3D physics engines focused on performance.
https://rapier.rs
Apache License 2.0
3.8k stars 236 forks source link

How do I detect collisions between 2 (or more entities) #537

Closed jakelacey2012 closed 9 months ago

jakelacey2012 commented 9 months ago

I have two components in my game a coin and a player, the player looks roughly like the following...

commands
        .spawn(RigidBody::KinematicPositionBased)
        .insert(KinematicCharacterController::default())
        .insert(Collider::ball(8.0))
        .insert(Restitution::coefficient(0.7))
        .insert(TransformBundle::from(Transform::from_xyz(0.0, 30.0, 10.0)))
        .insert(CollidingEntities::default())
        .insert((
            Player,
            SpriteSheetBundle {
                texture_atlas: r_texture_atlas_handle,
                sprite: TextureAtlasSprite::new(r_animation_indices.first),
                transform: Transform::from_xyz(-100.0, 0.0, 0.0),
                ..default()
            },
            r_animation_indices,
            AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)),
        ));

and the coin looks like this,

commands
        .spawn((
            Coin,
            Collider::cuboid(10.0, 10.0),
            SpriteSheetBundle {
                texture_atlas: texture_atlas_handle,
                sprite: TextureAtlasSprite::new(animation_indices.first),
                ..default()
            },
            animation_indices,
            AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)),
        ));

How can I create a system which allows me to detect when these two entities collide (when the player touches the coin?), I currently have a system which looks like the following but it is not working.

fn despawn_coin_on_contact(
    mut commands: Commands,
    players: Query<&CollidingEntities, With<Player>>,
    coins: Query<(), With<Coin>>,
) {
    for colliding_entities in &players {
        for entity in colliding_entities.iter() {
            if coins.contains(entity) {
                commands.entity(entity).despawn_recursive();
            }
        }
    }
}
jakelacey2012 commented 9 months ago

Will raise this in https://github.com/dimforge/bevy_rapier.