flame-engine / forge2d

A Dart port of Box2D
BSD 3-Clause "New" or "Revised" License
181 stars 26 forks source link

queryAABB does not work #73

Closed ghost closed 1 year ago

ghost commented 1 year ago

According to box2d documentations this code shoud work but nothing gets logged.

class Game extends Forge2DGame{

  Game(): super(zoom: 1, gravity: Vector2(0, 0));

  @override
  Future<void>? onLoad() async{
    super.onLoad();
    add(Planet(Vector2(100, 50)));
    add(Planet(Vector2(700, 300)));
    add(Player());
    world.queryAABB(MyCallBack(), AABB.withVec2(Vector2(-2000, -2000), Vector2(2000, 2000)));
  }
}

class MyCallBack extends QueryCallback{

  @override
  bool reportFixture(Fixture fixture) {
    print("Called");
    return true;
  }
}

class Player extends BodyComponent{
  @override
  Body createBody() {
    var bodyDef = BodyDef(type: BodyType.dynamic, position: Vector2(320, 220), linearVelocity: Vector2(-10, -10));
    var body = world.createBody(bodyDef);
    var shape = CircleShape();
    shape.radius = 15;
    body.createFixtureFromShape(shape);
    renderBody = true;
    return body;
  }
}

class Planet extends BodyComponent{
  final Vector2 position;
  Planet(this.position);

  @override
  Body createBody() {
    var bodyDef = BodyDef(type: BodyType.static, position: position);
    var body = world.createBody(bodyDef);
    body.createFixtureFromShape(CircleShape()..radius = 50);
    return body;
  }
}

There is clearly overlap between game objects and queried aabb but reportFixture never gets called. Have I missed something?

ghost commented 1 year ago

I think I found the problem

 world.queryAABB(MyCallBack(), AABB.withVec2(Vector2(-2000, -2000), Vector2(2000, 2000)));

It seems like you can't make this call in onLoad method. when I move this part to onMount or any other lifecycle methods, It works.