Search code examples
flutterdartflame

Detect collision with bottom of screen in Flame Engine?


Following the example here, is it possible to detect collisions with a specific side of the screen for example the bottom of the screen?

Flutter version: 2.2.3
Flame version: 1.0.0-releasecandidate.13

onCollision method of MyCollidable class

@override
  void onCollision(Set<Vector2> intersectionPoints, Collidable other) {
    if (other is ScreenCollidable) {
      _isWallHit = true;
      // Detect which side?
      return;
    }
  }

Solution

  • There is no built in method for this, but you can quite easily calculate which side it is that you are colliding with using the size of the game and convert the collision point to screen coordinates (this step isn't necessary if you are not changing the zoom level or moving the camera).

    The code would be something like this:

    class MyCollidable extends PositionComponent
        with Hitbox, Collidable, HasGameRef {
      
      ...
    
      void onCollision(Set<Vector2> intersectionPoints, Collidable other) {
        if (other is ScreenCollidable) {
          _isWallHit = true;
          final firstPoint = intersectionPoints.first;
          // If you don't move/zoom the camera this step can be skipped
          final screenPoint = gameRef.projectVector(firstPoint);
          final screenSize = gameRef.size;
          if (screenPoint.x == 0) {
            // Left wall (or one of the leftmost corners)
          } else if (screenPoint.y == 0) {
            // Top wall (or one of the upper corners)
          } else if (screenPoint.x == screenSize.x) {
            // Right wall (or one of the rightmost corners)
          } else if (screenPoint.y == screenSize.y) {
            // Bottom wall (or one of the bottom corners)
          }
          return;
        }
      }