flame_forge2d 0.20.0
flame_forge2d: ^0.20.0 copied to clipboard
Forge2D (Box2D) support for the Flame game engine. This uses the forge2d package and provides wrappers and components to be used inside Flame.
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/widgets.dart';
void main() {
runApp(const GameWidget.managed(gameFactory: Forge2DExample.new));
}
class Forge2DExample extends Forge2DGame {
@override
Future<void> onLoad() async {
await super.onLoad();
camera.viewport.add(FpsTextComponent());
world.add(Ball());
world.addAll(createBoundaries());
}
List<Component> createBoundaries() {
final visibleRect = camera.visibleWorldRect;
final topLeft = visibleRect.topLeft.toVector2();
final topRight = visibleRect.topRight.toVector2();
final bottomRight = visibleRect.bottomRight.toVector2();
final bottomLeft = visibleRect.bottomLeft.toVector2();
return [
Wall(topLeft, topRight),
Wall(topRight, bottomRight),
Wall(bottomLeft, bottomRight),
Wall(topLeft, bottomLeft),
];
}
}
/// A ball the size of a football, in a world measured in meters.
///
/// Forge2D is tuned for bodies roughly between 0.1 and 10 meters, so the
/// world is laid out at a realistic scale and the camera decides how large
/// that ends up being on screen.
class Ball extends BodyComponent with TapCallbacks {
Ball({Vector2? initialPosition})
: super(
shapeSpecs: [
ShapeSpec(
Circle(radius: 0.5),
ShapeDef(
material: SurfaceMaterial(restitution: 0.8, friction: 0.4),
),
),
],
bodyDef: BodyDef(
angularDamping: 0.8,
position: initialPosition ?? Vector2.zero(),
type: BodyType.dynamic,
),
);
@override
void onTapDown(_) {
body.applyLinearImpulse(Vector2.random() * 5);
}
}
class Wall extends BodyComponent {
final Vector2 _start;
final Vector2 _end;
Wall(this._start, this._end);
@override
Body createBody() {
final shapeDef = ShapeDef(material: SurfaceMaterial(friction: 0.3));
final bodyDef = BodyDef(
position: Vector2.zero(),
);
return world.createBody(bodyDef)
..createShape(Segment(point1: _start, point2: _end), shapeDef);
}
}