Search code examples
flutterdartflame

In spite of onCollision handling my character falls through the platform


This is the mechanism I use to prevent this bad accident happening to my beloved character:

void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
    print(
        "other is $other and intersectionPoints length is ${intersectionPoints.length}");
    if (other is Brick && intersectionPoints.length == 2) {
      isOnGround = true;
      final intersectionsVector=
          (intersectionPoints.elementAt(0) + intersectionPoints.elementAt(1)) /
              2;
      final collisionVector = absoluteCenter - intersectionsVector;
      final penetrationDistance = size.x / 2 - collisionVector.length;
      collisionVector.normalize();
      if (Vector2(0, -1).dot(collisionVector) > 0.9) {
        isOnGround = true;
      }

      position += collisionVector.scaled(penetrationDistance);
    }

    super.onCollision(intersectionPoints, other);
  }

Most of my game and even variables are inspired from the Flame's Ember character, The only difference is Ember game doesn't use cameraComponent.follow(player) but I do. Everthing works fine and my character is walking happily and all of a sudden he gets passed through the ground and dies.

So I added this to see what is what:

  print(
        "other is $other and intersectionPoints length is ${intersectionPoints.length}");

The only problem I see is intersectionPoints length are some times 1 and maybe that's the time my character falls. and I don't know why. I'm using CircleHitBox for my player and RectanglehitBox for my Bricks(platform). So how can I handle this better. Thank you


Solution

  • Just like you have noticed, intersectionPoints doesn't necessarily contain 2 entries, you should even get an error when that happens since you are doing elementAt(1) and there might not be and element on that index.

    If you want to take the average of the intersection points I recommend to do something like this:

    final Vector2 average = Vector2.zero;
    for (final point in intersectionPoints) {
      average.add(point);
    }
    average.scale(1/intersectionPoints.length);