flutterflame

how to manage collision in flutter flame when multiple objects of the same type collide?


I am trying to make a bubble shooter demo that has 3 types of bubbles (fish,dog and cat).
They are all circle components.
For example when i launch a dog bubble to a group of bubbles it explodes all the dog bubbles that exist in the screen,
is there a way to make bubbles explodes only the ones that are close to the one who got hit by the launch bubble?

@override
void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {     
  super.onCollision(intersectionPoints, other);
  if (other is DogBubble) {
    if (position.distanceTo(other.position) <= radius + other.radius) {
      removeFromParent();
    }
  }
}

I've tried a couple of ways to remove only the one who got hit and other remove all the dogs bubble in the screen.

I expect that when a bubble gets hit all of the bubbles that close to it will be removed.


Solution

  • If your DogBubbles are in the world you can query them and do the check (if they have another component as a parent, use that one to query for them). Also, use onCollisionStart instead of onCollision, since you're not observing continues collisions.

    @override
    void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {     
      super.onCollision(intersectionPoints, other);
      if (other is DogBubble) {
        for(final bubble in world.query<DogBubble>()) {
          if (position.distanceTo(bubble.position) <= radius + bubble.radius) {
            removeFromParent();
          }
        }
      }
    }
    

    If you don't have access to your world in the component, add the HasWorldReference mixin to the component and it will provide you with the world variable inside of the component.