flutterdartflameforge2d

Creating an L-Shaped Body with Flame Forge2D in Flutter


I'm currently working on a project where I need to create an L-shaped body using Flame Forge2D. I've defined the shape using the PolygonShape class with the following vertices:

final List<Vector2> vertices = [
  Vector2(-4, -4),
  Vector2(0, -4),
  Vector2(0, 0),
  Vector2(4, 0),
  Vector2(4, 4),
  Vector2(-4, 4),
];

However, when I create the body with this shape, the entire area gets filled, and I'm looking to have only the L-shaped region filled.

PolygonShape Issue

Here's a snippet of my current code:

class LShapedBody extends BodyComponent {
  final Vector2 _position;
  final double width;
  final double height;

  LShapedBody(this._position, this.width, this.height);

  @override
  Body createBody() {
    final shape = PolygonShape();

    final List<Vector2> vertices = [
      Vector2(-1, -1),
      Vector2(0, -1),
      Vector2(0, 0),
      Vector2(1, 0),
      Vector2(1, 1),
      Vector2(-1, 1),
    ];

    shape.set(vertices);
    final fixtureDef = FixtureDef(shape);

    final bodyDef = BodyDef(type: BodyType.static, position: _position);
    return world.createBody(bodyDef)..createFixture(fixtureDef);
  }
}

I've tried adjusting the vertices, but I haven't been successful in achieving the desired result. If anyone has experience with Flame Forge2D and creating non-rectangular bodies, could you please guide me on how to properly define the vertices or any additional steps needed?


Solution

  • Polygons in Box2D/Forge2D needs to be convex, which an L isn't.

    What you have to do here is to create to fixtures and attach them to the body, one for the upper part of the L, and one for the lying part. So basically just two rectangles.