Search code examples
flutterflameforge2d

How can I draw a rectangle in flame_forge2d?


In Love2D, there is a function called newRectangleShape: https://love2d.org/wiki/love.physics.newRectangleShape

However, I couldn't find a similar function in flame_forge2d: https://pub.dev/documentation/forge2d/latest/forge2d/

Nor in Box2D: https://box2d.org/documentation/group__shape.html

Since both Love2D and flame_forge2d internally use Box2D (or a port of it), I assume that Love2D provides RectangleShape to make it easier to work with rectangles. If that’s the case, how can I achieve something similar in flame_forge2d?

My ultimate goal is to create a kinematic rectangle and rotate it, as discussed in this question: https://gamedev.stackexchange.com/questions/212558/what-does-the-phrase-kinematic-bodies-do-not-collide-with-other-kinematic-or-st

For now, however, I’d like to focus solely on how to create a rectangle.


If possible, I would like to add a rectangle beneath the falling circle in the example here: https://github.com/flame-engine/flame/blob/main/packages/flame_forge2d/example/lib/main.dart

Ultimately, I want to rotate the rectangle and make it collide with the circle.

It seems that I might be able to achieve this by referring to the Wall in the example. However, since Wall is not being rendered, it's hard to understand how to use it as a reference.


Solution

  • A rectangle is a polygon, so that is the shape that you should be using.

      @override
      Body createBody() {
        final shape = PolygonShape()..setAsBoxXY(10, 5);
        final fixtureDef = FixtureDef(shape);
    
        final bodyDef = BodyDef(position: _position);
        final body = world.createBody(bodyDef);
        return body..createFixture(fixtureDef);
      }
    

    PS. There are examples with rectangles in the directory you were looking in: https://examples.flame-engine.org/#/flame_forge2d_Domino_example