how to let SpriteAnimationComponent follow BodyComponent, which can fall due to gravity. currently SpriteAnimationComponent still keep in the air, here is my code:
class Chick extends BodyComponent {
Vector2 fallPosition;
SpriteAnimationComponent chick = SpriteAnimationComponent();
Chick({
this.fallPosition,
});
final spriteSize = Vector2(32, 34) / 2;
@override
Future<void> onLoad() async {
await super.onLoad();
var spriteData = SpriteAnimationData.sequenced(
amount: 14, stepTime: 0.1, textureSize: Vector2(32, 34));
chick = SpriteAnimationComponent.fromFrameData(
spriteSize, ImageTool.image('chicken.png'), spriteData)
..x = fallPosition.x
..y = fallPosition.y
..anchor = Anchor.center
..size = spriteSize;
await addChild(chick);
}
@override
void update(double dt) {
chick.position = body.position;
print('body.position ! ${body.position} == $fallPosition}');
super.update(dt);
}
@override
Body createBody() {
debugMode = true;
final shape = CircleShape()..radius = spriteSize.x / 2;
var position = fallPosition.clone();
var worldPosition = viewport.getScreenToWorld(position);
final fixtureDef = FixtureDef()
..shape = shape
..restitution = 0.1
..density = 0.1
..friction = 0.1;
final bodyDef = BodyDef()
..userData = this
..angularDamping = 0.1
..position = worldPosition
..type = BodyType.DYNAMIC;
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
}
I realize fallPosition, fallPosition, and chick.position has different value, but I dont know how to make this SpriteAnimationComponent follow Body, thanks for any help!
Add the SpriteBodyComponent
as a child to the BodyComponent
by simply running add
, and remove the attempts that you have at synchronizing the positions, this will be done automatically once you have added it as a child.
To do this you also need to upgrade to a newer version of Flame (preferably v1.4.0 or newer) and a new version of flame_forge2d
(> 0.12.3). Do note that addChild
has been renamed to add
.