I'm playing around with Forge2d on Flutter Flame and created a Ninja which throws Kanuies (a character shooting bullets basically). If I create Kanuies and the Ninja separately then add them separately to the game world, all will be fine. However, I want the Ninja class to be responsible for login for throwing the Kanui. So I was wondering what is the right way to add a bullet component to a character component in Forge2d.
In my current code, inside Ninja Class, if I call add(Kanui)
there will be no graphics shown about Kanuie NOT even with debugMode=true
.
However, if use addToParrent(Kanui)
it will be fine again.
Below is the link to my code. Please have a look and suggest corrections. I'll provide some snippets here as well.
Ninja Class:
class MyGirl extends BodyComponent {
late SpriteAnimationComponent component;
Queue<MyGirlKanui> kanuies = Queue<MyGirlKanui>();
@override
Future<void> onl oad() async {
await super.onLoad();
idleAnimation = await gameRef.loadSpriteAnimation("red_girl/idle_spriteSheet.png", idleAnimationData);
component = SpriteAnimationComponent()
..animation = idleAnimation
..size = Vector2.all(6)
..anchor = Anchor.center;
add(component);
kanuies.add(MyGirlKanui(initialPosition));
}
@override
Body createBody() {
final shape = PolygonShape()..setAsBoxXY(3, 3);
final fixtureDefinition = FixtureDef(shape, density: 2, restitution: 0.1, friction: 2);
final bodyDefinition = BodyDef(position: initialPosition, type: BodyType.dynamic)..fixedRotation = true;
return world.createBody(bodyDefinition)..createFixture(fixtureDefinition);
}
throwKanui() async {
if (kanuies.isNotEmpty) {
var kanui = kanuies.removeFirst();
// await parent?.add(kanui);
await add(kanui);
kanui.component.position = component.position;
kanui.body.linearVelocity.x = 30;
}
}
I call the throw method when a UI button is pressed.
CodePudding user response:
In Forge2D you shouldn't add any bodies as children to other components.
You can add the HasGameRef<Forge2DGame>
mixin to the component and then you can add the bullets directly to the game.
Also don't forget to put the body of the bullet to isBullet = true
if the "bullet" is moving very fast, otherwise you could end up with tunneling (where the body passes through the object that it is supposed to hit).