### Complete main.dart Example Source: https://docs.flame-engine.org/latest/tutorials/space_shooter/step_1.html A consolidated view of the main.dart file, including the game setup, player component, and game logic for initial rendering. ```dart import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flutter/material.dart'; void main() { runApp(GameWidget(game: SpaceShooterGame())); } class Player extends PositionComponent { static final _paint = Paint()..color = Colors.white; @override void render(Canvas canvas) { canvas.drawRect(size.toRect(), _paint); } } class SpaceShooterGame extends FlameGame { @override Future onLoad() async { add( Player() ..position = size / 2 ..width = 50 ..height = 100 ..anchor = Anchor.center, ); } } ``` -------------------------------- ### RouterComponent Setup Example Source: https://docs.flame-engine.org/latest/flame/router.html Demonstrates how to set up a RouterComponent with various routes, including a home page, level selector, settings, a pause route, and an overlay route. ```dart class MyGame extends FlameGame { late final RouterComponent router; @override void onLoad() { add( router = RouterComponent( routes: { 'home': Route(HomePage.new), 'level-selector': Route(LevelSelectorPage.new), 'settings': Route(SettingsPage.new, transparent: true), 'pause': PauseRoute(), 'confirm-dialog': OverlayRoute.existing(), }, initialRoute: 'home', ), ); } } class PauseRoute extends Route { ... } ``` -------------------------------- ### ValueRoute Example Game Setup Source: https://docs.flame-engine.org/latest/flame/router.html Sets up the main FlameGame with a RouterComponent and defines the initial route. The RouterComponent manages navigation between different routes within the game. ```dart class ValueRouteExample extends FlameGame { late final RouterComponent router; @override Future onLoad() async { router = RouterComponent( routes: {'home': Route(HomePage.new)}, initialRoute: 'home', ); add(router); } } ``` -------------------------------- ### Ray Casting Example with FlameGame Source: https://docs.flame-engine.org/latest/flame/collision_detection.html Demonstrates a full example of ray casting within a Flame game, including setup, rendering, and dynamic ray updates. ```dart import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; import 'package:flame/palette.dart'; import 'package:flutter/material.dart'; class RayCastExample extends FlameGame with HasCollisionDetection { final origin = Vector2(20, 20); final direction = Vector2(1, 0); final velocity = 60; double get resetPosition => -canvasSize.y; Paint paint = Paint()..color = Colors.red.withValues(alpha: 0.6); RaycastResult? result; @override Future onLoad() async { final paint = BasicPalette.gray.paint() ..style = PaintingStyle.stroke ..strokeWidth = 2.0; add(ScreenHitbox()); add( CircleComponent( position: canvasSize / 2, radius: 30, paint: paint, children: [CircleHitbox()], ), ); } @override void update(double dt) { super.update(dt); final ray = Ray2( origin: origin, direction: direction, ); result = collisionDetection.raycast(ray); origin.y += velocity * dt; if (origin.y > canvasSize.y) { origin.y += resetPosition; } } @override void render(Canvas canvas) { super.render(canvas); if (result != null && result!.isActive) { final originOffset = origin.toOffset(); final intersectionPoint = result!.intersectionPoint!.toOffset(); canvas.drawLine( originOffset, intersectionPoint, paint, ); canvas.drawCircle(originOffset, 10, paint); } } } ``` -------------------------------- ### Install Documentation Dependencies Source: https://docs.flame-engine.org/latest/development/documentation.html Installs the necessary requirements for building the documentation site using Melos. ```bash melos run doc-setup ``` -------------------------------- ### Flame Ray Tracing Example Source: https://docs.flame-engine.org/latest/flame/collision_detection.html Demonstrates ray tracing with multiple reflections in Flame. It visualizes the traced rays and their intersections with hitboxes. Tap to start and reset the tracing. ```dart import 'dart:math'; import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; import 'package:flame/palette.dart'; import 'package:flutter/material.dart'; class RayTraceExample extends FlameGame with HasCollisionDetection, TapCallbacks { Paint paint = Paint()..color = Colors.red.withValues(alpha: 0.6); bool isClicked = false; Vector2 get origin => canvasSize / 2; RaycastResult? result; final Ray2 _ray = Ray2.zero(); final boxPaint = BasicPalette.gray.paint() ..style = PaintingStyle.stroke ..strokeWidth = 2.0; final List> results = []; @override Future onLoad() async { add( CircleComponent( radius: min(size.x, size.y) / 2, paint: boxPaint, children: [CircleHitbox()], ), ); } var _timePassed = 0.0; @override void update(double dt) { super.update(dt); if (isClicked) { _timePassed += dt; } result = collisionDetection.raycast(_ray); _ray.origin.setFrom(origin); _ray.direction ..setValues(1, 1) ..normalize(); collisionDetection .raytrace( _ray, maxDepth: min((_timePassed * 8).ceil(), 1000), out: results, ) .toList(); } @override void render(Canvas canvas) { super.render(canvas); var originOffset = origin.toOffset(); for (final result in results) { if (!result.isActive) { continue; } final intersectionPoint = result.intersectionPoint!.toOffset(); canvas.drawLine( originOffset, intersectionPoint, paint, ); originOffset = intersectionPoint; } } @override void onTapUp(TapUpEvent event) { if (!isClicked) { isClicked = true; return; } _timePassed = 0; } } ``` -------------------------------- ### GameWidget with overlay example Source: https://docs.flame-engine.org/latest/flame/game_widget.html This example demonstrates how to provide a map of overlay widgets that can be dynamically shown or hidden during the game's execution. ```dart void main() { runApp( GameWidget( game: MyGame(), overlayBuilderMap: { 'PauseMenu': (context, game) { return Container( color: const Color(0xFF000000), child: Text('A pause menu'), ); }, }, ), ); } ``` -------------------------------- ### PulleyJoint Example Implementation Source: https://docs.flame-engine.org/latest/bridge_packages/flame_forge2d/joints.html A complete example demonstrating the setup and usage of a PulleyJoint within a Flame Forge2D game. It includes creating draggable boxes and static balls to represent the pulley system. ```dart import 'dart:ui'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/balls.dart'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boxes.dart'; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class PulleyJointExample extends Forge2DGame { static const description = ''' This example shows how to use a `PulleyJoint`. Drag one of the boxes and see how the other one gets moved by the pulley '''; @override Future onLoad() async { super.onLoad(); final distanceFromCenter = camera.visibleWorldRect.width / 5; final firstPulley = Ball( Vector2(-distanceFromCenter, -10), bodyType: BodyType.static, ); final secondPulley = Ball( Vector2(distanceFromCenter, -10), bodyType: BodyType.static, ); final firstBox = DraggableBox( startPosition: Vector2(-distanceFromCenter, 20), width: 5, height: 10, ); final secondBox = DraggableBox( startPosition: Vector2(distanceFromCenter, 20), width: 7, height: 10, ); world.addAll([firstBox, secondBox, firstPulley, secondPulley]); await Future.wait([ firstBox.loaded, secondBox.loaded, firstPulley.loaded, secondPulley.loaded, ]); final joint = createJoint(firstBox, secondBox, firstPulley, secondPulley); world.add(PulleyRenderer(joint: joint)); } PulleyJoint createJoint( Box firstBox, Box secondBox, Ball firstPulley, Ball secondPulley, ) { final pulleyJointDef = PulleyJointDef() ..initialize( firstBox.body, secondBox.body, firstPulley.center, secondPulley.center, firstBox.body.worldPoint(Vector2(0, -firstBox.height / 2)), secondBox.body.worldPoint(Vector2(0, -secondBox.height / 2)), 1, ); final joint = PulleyJoint(pulleyJointDef); world.createJoint(joint); return joint; } } class PulleyRenderer extends Component { PulleyRenderer({required this.joint}); final PulleyJoint joint; @override void render(Canvas canvas) { canvas.drawLine( joint.anchorA.toOffset(), joint.getGroundAnchorA().toOffset(), debugPaint, ); canvas.drawLine( joint.anchorB.toOffset(), joint.getGroundAnchorB().toOffset(), debugPaint, ); canvas.drawLine( joint.getGroundAnchorA().toOffset(), joint.getGroundAnchorB().toOffset(), debugPaint, ); } } ``` -------------------------------- ### Basic RouterComponent Setup Source: https://docs.flame-engine.org/latest/flame/router.html Demonstrates the basic setup of a RouterComponent with several routes defined. This includes 'home', 'level1', 'level2', and 'pause' routes, with 'level2' configured to not maintain its state. The initial route is set to 'home'. ```dart import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; import 'package:flame/rendering.dart'; import 'package:flutter/rendering.dart'; class RouterGame extends FlameGame { late final RouterComponent router; @override Future onLoad() async { add( router = RouterComponent( routes: { 'home': Route(StartPage.new), 'level1': WorldRoute(Level1Page.new), 'level2': WorldRoute(Level2Page.new, maintainState: false), 'pause': PauseRoute(), }, initialRoute: 'home', ), ); } } ``` -------------------------------- ### Example of a User-Defined Command with Arguments Source: https://docs.flame-engine.org/latest/other_modules/jenny/language/commands/user_defined_commands.html This example demonstrates how to define a user-defined command with arguments, including expressions that are evaluated at runtime. Ensure expressions are enclosed in curly braces. ```yarn <> ``` -------------------------------- ### MouseJoint Example Implementation Source: https://docs.flame-engine.org/latest/bridge_packages/flame_forge2d/joints.html Implements a game with a MouseJoint that allows a ball to follow the mouse cursor when dragged. Includes setup for boundaries and the ball. ```dart import 'package:examples/stories/bridge_libraries/flame_forge2d/revolute_joint_with_motor_example.dart'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/balls.dart'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart'; import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class MouseJointExample extends Forge2DGame { static const description = ''' In this example we use a `MouseJoint` to make the ball follow the mouse when you drag it around. '''; MouseJointExample() : super(gravity: Vector2(0, 10.0), world: MouseJointWorld()); } class MouseJointWorld extends Forge2DWorld with DragCallbacks, HasGameReference { late Ball ball; late Body groundBody; MouseJoint? mouseJoint; @override Future onLoad() async { super.onLoad(); final boundaries = createBoundaries(game); addAll(boundaries); final center = Vector2.zero(); groundBody = createBody(BodyDef()); ball = Ball(center, radius: 5); add(ball); add(CornerRamp(center)); add(CornerRamp(center, isMirrored: true)); } @override void onDragStart(DragStartEvent info) { super.onDragStart(info); if (mouseJoint != null) { return; } final mouseJointDef = MouseJointDef() ..maxForce = 3000 * ball.body.mass * 10 ..dampingRatio = 0.1 ..frequencyHz = 5 ..target.setFrom(ball.body.position) ..collideConnected = false ..bodyA = groundBody ..bodyB = ball.body; mouseJoint = MouseJoint(mouseJointDef); createJoint(mouseJoint!); } @override void onDragUpdate(DragUpdateEvent info) { mouseJoint?.setTarget(info.localEndPosition); } @override void onDragEnd(DragEndEvent info) { super.onDragEnd(info); destroyJoint(mouseJoint!); mouseJoint = null; } } ``` -------------------------------- ### Using the prompt command in Yarn Source: https://docs.flame-engine.org/latest/other_modules/jenny/runtime/command_storage.html This example shows how to use the registered `<>` command within a Yarn script to get user input and store it in a variable. ```yarn <> title: Greeting --- Guide: Hello, my name is Jenny, and you? <> <> // Store the name for later Guide: Nice to meet you, {$player} === ``` -------------------------------- ### Basic FlameGame Implementation Source: https://docs.flame-engine.org/latest/flame/game.html This example demonstrates a simple Flame game setup. It includes a custom World and a SpriteComponent, showing how to add components in the constructor and within the onLoad method. It's used to initialize and run a Flame game within a Flutter application. ```dart import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flutter/widgets.dart'; /// A component that renders the crate sprite, with a 16 x 16 size. class MyCrate extends SpriteComponent { MyCrate() : super(size: Vector2.all(16)); @override Future onLoad() async { sprite = await Sprite.load('crate.png'); } } class MyWorld extends World { @override Future onLoad() async { await add(MyCrate()); } } void main() { final myGame = FlameGame(world: MyWorld()); runApp( GameWidget(game: myGame), ); } ``` -------------------------------- ### Basic GameWidget Setup Source: https://docs.flame-engine.org/latest/README.html This snippet shows the minimal setup required to run a Flame game within a Flutter application using the GameWidget. ```dart import 'package:flame/game.dart'; import 'package:flutter/material.dart'; void main() { runApp( GameWidget( game: FlameGame(), ), ); } ``` -------------------------------- ### WorldRoute Example: MyWorld2 Source: https://docs.flame-engine.org/latest/flame/router.html Another example World class, demonstrating additional components like an EnemyComponent. ```dart class MyWorld2 extends World { @override Future onLoad() async { add(BackgroundComponent()); add(PlayerComponent()); add(EnemyComponent()); } } ``` -------------------------------- ### Example Usage Source: https://docs.flame-engine.org/latest/flame/layout/padding_component.html Demonstrates how to create and use a PaddingComponent with a child component. ```APIDOC ## Example usage: ``` PaddingComponent( padding: EdgeInsets.all(10), child: TextComponent(text: 'bar') ); ``` ``` -------------------------------- ### Basic Rive Component Initialization Source: https://docs.flame-engine.org/latest/bridge_packages/flame_rive/rive.html Initializes a RiveComponent with an artboard and state machine. This example demonstrates a simpler setup without explicit data binding for inputs. ```dart class RiveExampleGame extends FlameGame { @override Future onLoad() async { final file = await File.asset( 'assets/rewards.riv', riveFactory: Factory.rive, ); final artboard = await loadArtboard(file!); final stateMachine = artboard.defaultStateMachine(); if (stateMachine != null) { final viewModel = file.defaultArtboardViewModel(artboard); if (viewModel != null) { final viewModelInstance = viewModel.createDefaultInstance(); if (viewModelInstance != null) { stateMachine.bindViewModelInstance(viewModelInstance); final coinAmount = viewModelInstance.viewModel('Coin')?.number('Item_Value'); coinAmount?.value = 100; } } } add( RiveComponent( artboard: artboard, stateMachine: stateMachine, size: Vector2.all(550), ), ); } } ``` -------------------------------- ### Check Flutter Installation Source: https://docs.flame-engine.org/latest/tutorials/bare_flame_game.html Verify that your Flutter SDK is installed correctly and accessible from the command line. Ensure your Flutter version is at least 3.13.0. ```bash $ flutter doctor Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 3.13.7, on macOS 13.6 22G120 darwin-arm64, locale en) [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0) [✓] Xcode - develop for iOS and macOS (Xcode 15.0) [✓] Chrome - develop for the web [✓] Android Studio (version 2021.2) [✓] IntelliJ IDEA Community Edition (version 2022.2.2) [✓] VS Code (version 1.83.0) [✓] Connected device (2 available) [✓] Network resources • No issues found! ``` -------------------------------- ### Interactive Color Quiz Example Source: https://docs.flame-engine.org/latest/other_modules/jenny/language/commands/set.html An example demonstrating how to use `<>` within a narrative choice structure to update a variable based on user input. It also shows a modifying assignment. ```text <> title: ColorQuiz --- What is your favorite color? -> White <> -> Red <> -> Yellow <> -> Blue Oh, Nice! Which shade of blue? -> Azure -> Cerulean -> Lapis Lazuli Umm, I don't know how to spell that. I'll just put you down as "blue". <> -> Black <> That's mine too! <> -> Prefer not to tell Aww... Maybe if I ask again really nicely? <> === ``` -------------------------------- ### Simple Yarn Dialogue Example Source: https://docs.flame-engine.org/latest/other_modules/jenny/jenny.html A basic example of a .yarn file demonstrating a simple dialogue exchange between two characters. This format is designed to be intuitive and easily understood. ```yarn title: Scene1_Gregory_and_Sampson --- Sampson: Gregory, on my word, we'll not carry coals. Gregory: No, for then we should be colliers. Sampson: I mean, an we be in choler, we'll draw. Gregory: Ay, while you live, draw your neck out of collar. Sampson: I strike quickly being moved. Gregory: But thou art not quickly moved to strike. === ``` -------------------------------- ### GearJoint Example Source: https://docs.flame-engine.org/latest/bridge_packages/flame_forge2d/joints.html Demonstrates the usage of GearJoint to connect two other joints, creating a gear-like mechanism. The example includes setting up prismatic and revolute joints and then linking them with a GearJoint, specifying a gear ratio. ```dart import 'dart:ui'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/balls.dart'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boxes.dart'; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class GearJointExample extends Forge2DGame { static const description = ''' This example shows how to use a `GearJoint`. Drag the box along the specified axis and observe gears respond to the translation. '''; GearJointExample() : super(world: GearJointWorld()); } class GearJointWorld extends Forge2DWorld with HasGameReference { late PrismaticJoint prismaticJoint; Vector2 boxAnchor = Vector2.zero(); double boxWidth = 2; double ball1Radius = 4; double ball2Radius = 2; @override Future onLoad() async { super.onLoad(); final box = DraggableBox( startPosition: boxAnchor, width: boxWidth, height: 20, ); add(box); final ball1Anchor = boxAnchor - Vector2(boxWidth / 2 + ball1Radius, 0); final ball1 = Ball(ball1Anchor, radius: ball1Radius); add(ball1); final ball2Anchor = ball1Anchor - Vector2(ball1Radius + ball2Radius, 0); final ball2 = Ball(ball2Anchor, radius: ball2Radius); add(ball2); await Future.wait([box.loaded, ball1.loaded, ball2.loaded]); prismaticJoint = createPrismaticJoint(box.body, boxAnchor); final revoluteJoint1 = createRevoluteJoint(ball1.body, ball1Anchor); final revoluteJoint2 = createRevoluteJoint(ball2.body, ball2Anchor); createGearJoint(prismaticJoint, revoluteJoint1, 1); createGearJoint(revoluteJoint1, revoluteJoint2, 0.5); add(JointRenderer(joint: prismaticJoint, anchor: boxAnchor)); } PrismaticJoint createPrismaticJoint(Body box, Vector2 anchor) { final groundBody = createBody(BodyDef()); final prismaticJointDef = PrismaticJointDef() ..initialize( groundBody, box, anchor, Vector2(0, 1), ) ..enableLimit = true ..lowerTranslation = -10 ..upperTranslation = 10; final joint = PrismaticJoint(prismaticJointDef); createJoint(joint); return joint; } RevoluteJoint createRevoluteJoint(Body ball, Vector2 anchor) { final groundBody = createBody(BodyDef()); final revoluteJointDef = RevoluteJointDef() ..initialize( groundBody, ball, anchor, ); final joint = RevoluteJoint(revoluteJointDef); createJoint(joint); return joint; } void createGearJoint(Joint first, Joint second, double gearRatio) { final gearJointDef = GearJointDef() ..bodyA = first.bodyA ..bodyB = second.bodyA ..joint1 = first ..joint2 = second ..ratio = gearRatio; final joint = GearJoint(gearJointDef); createJoint(joint); } } class JointRenderer extends Component { JointRenderer({required this.joint, required this.anchor}); final PrismaticJoint joint; final Vector2 anchor; final Vector2 p1 = Vector2.zero(); final Vector2 p2 = Vector2.zero(); @override void render(Canvas canvas) { p1 ..setFrom(joint.getLocalAxisA()) ..scale(joint.getLowerLimit()) ..add(anchor); p2 ..setFrom(joint.getLocalAxisA()) ..scale(joint.getUpperLimit()) ..add(anchor); canvas.drawLine(p1.toOffset(), p2.toOffset(), debugPaint); } } ``` -------------------------------- ### Golden Test Setup in Dart Source: https://docs.flame-engine.org/latest/development/testing_guide.html Used for verifying visual output. Define the game setup, size, and golden file path. Avoid using text in golden tests due to rendering inconsistencies. ```dart testGolden( 'the name of the test', (game) async { // Set up the game by adding the necessary components // You can add `expect()` checks here too, if you want to }, size: Vector2(300, 200), goldenFile: '.../_goldens/my_test_file.png', ); ``` -------------------------------- ### Dynamic Parameter Example in .yarn Source: https://docs.flame-engine.org/latest/other_modules/jenny/runtime/markup_attribute.html Shows how markup attributes can include dynamic parameters, such as a color variable that can change at runtime. ```plaintext My [i]favorite[/i] color is [bb color=$color]{$color}[/bb]. ``` -------------------------------- ### DelayedEffectController Example Source: https://docs.flame-engine.org/latest/flame/effects/effect_controllers.html Introduce a delay before an effect controller starts executing its child controller. During the delay, the effect is considered not started. ```dart final controller = DelayedEffectController(LinearEffectController(1), delay: 5); ``` -------------------------------- ### Initialize and Push to GitHub Source: https://docs.flame-engine.org/latest/tutorials/bare_flame_game.html Use these Git commands to initialize a new repository, add all project files, commit them, link to a remote origin, and push the changes to GitHub. ```bash git init git add --all git commit -m 'Initial commit' git remote add origin https://github.com/your-github-username/syzygy.git git branch -M main git push -u origin main ``` -------------------------------- ### Example Markup in .yarn Source: https://docs.flame-engine.org/latest/other_modules/jenny/runtime/markup_attribute.html Illustrates how text ranges are demarcated with markup tags like [b] and [link] in a .yarn file. ```plaintext [b]Jenny[/b] is a library based on \n [link url="docs.yarnspinner.dev"]YarnSpinner[/link] for Unity. ``` -------------------------------- ### RopeJoint Example Implementation Source: https://docs.flame-engine.org/latest/bridge_packages/flame_forge2d/joints.html An example demonstrating the use of `RopeJoint` within a Flame Forge2D game. This setup includes creating a draggable handle and a series of connected balls to form a rope effect. ```dart import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/balls.dart'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boxes.dart'; import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; class RopeJointExample extends Forge2DGame { static const description = ''' This example shows how to use a `RopeJoint`. Drag the box handle along the axis and observe the rope respond to the movement. '''; RopeJointExample() : super(world: RopeJointWorld()); } class RopeJointWorld extends Forge2DWorld with DragCallbacks, HasGameReference { double handleWidth = 6; @override Future onLoad() async { super.onLoad(); final handleBody = await createHandle(); createRope(handleBody); } Future createHandle() async { final anchor = game.screenToWorld(Vector2(0, 100))..x = 0; final box = DraggableBox( startPosition: anchor, width: handleWidth, height: 3, ); await add(box); createPrismaticJoint(box.body, anchor); return box.body; } Future createRope(Body handle) async { const length = 50; var prevBody = handle; for (var i = 0; i < length; i++) { final newPosition = prevBody.worldCenter + Vector2(0, 1); final ball = Ball(newPosition, radius: 0.5, color: Colors.white); await add(ball); createRopeJoint(ball.body, prevBody); prevBody = ball.body; } } void createPrismaticJoint(Body box, Vector2 anchor) { final groundBody = createBody(BodyDef()); final halfWidth = game.screenToWorld(Vector2.zero()).x.abs(); final prismaticJointDef = PrismaticJointDef() ..initialize( box, groundBody, anchor, Vector2(1, 0), ) ..enableLimit = true ..lowerTranslation = -halfWidth + handleWidth / 2 ..upperTranslation = halfWidth - handleWidth / 2; final joint = PrismaticJoint(prismaticJointDef); createJoint(joint); } void createRopeJoint(Body first, Body second) { final ropeJointDef = RopeJointDef() ..bodyA = first ..localAnchorA.setFrom(first.getLocalCenter()) ..bodyB = second ..localAnchorB.setFrom(second.getLocalCenter()) ..maxLength = (second.worldCenter - first.worldCenter).length; createJoint(RopeJoint(ropeJointDef)); } } ``` -------------------------------- ### Game Setup with Outline Post Process Source: https://docs.flame-engine.org/latest/tutorials/basic_shader/step2.html Sets up the main game loop and world, adding both a standard sprite and an outlined sprite for comparison. Ensure the shader asset path is correct to avoid runtime errors. ```dart import 'package:flutter/material.dart'; import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:basic_shader_tutorial/sword_component.dart'; void main() { runApp( GameWidget(game: MyGame()), ); } class MyGame extends FlameGame { MyGame() : super(world: MyWorld()); @override Color backgroundColor() => Colors.green; } class MyWorld extends World { @override Future onLoad() async { add( SwordSprite() ..position = Vector2(-200, 0) ..anchor = Anchor.center, ); add( OutlinedSwordSprite( position: Vector2(200, 0), anchor: Anchor.center, ), ); } } ``` -------------------------------- ### RevoluteJoint Example in Flame Forge2D Source: https://docs.flame-engine.org/latest/bridge_packages/flame_forge2d/joints.html A complete example demonstrating the use of RevoluteJoint in a Flame Forge2D application. It includes setup for the game, world, and a custom component that creates bodies connected by a revolute joint upon tap. ```dart import 'dart:math'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/balls.dart'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart'; import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class RevoluteJointExample extends Forge2DGame { static const description = ''' In this example we use a joint to keep a body with several fixtures stuck to another body. Tap the screen to add more of these combined bodies. '''; RevoluteJointExample() : super(gravity: Vector2(0, 10.0), world: RevoluteJointWorld()); } class RevoluteJointWorld extends Forge2DWorld with TapCallbacks, HasGameReference { @override Future onLoad() async { super.onLoad(); addAll(createBoundaries(game)); } @override void onTapDown(TapDownEvent info) { super.onTapDown(info); final ball = Ball(info.localPosition); add(ball); add(CircleShuffler(ball)); } } class CircleShuffler extends BodyComponent { final Ball ball; CircleShuffler(this.ball); @override Body createBody() { final bodyDef = BodyDef( type: BodyType.dynamic, position: ball.body.position.clone(), ); const numPieces = 5; const radius = 6.0; final body = world.createBody(bodyDef); for (var i = 0; i < numPieces; i++) { final xPos = radius * cos(2 * pi * (i / numPieces)); final yPos = radius * sin(2 * pi * (i / numPieces)); final shape = CircleShape() ..radius = 1.2 ..position.setValues(xPos, yPos); final fixtureDef = FixtureDef( shape, density: 50.0, friction: 0.1, restitution: 0.9, ); body.createFixture(fixtureDef); } final jointDef = RevoluteJointDef() ..initialize(body, ball.body, body.position); world.createJoint(RevoluteJoint(jointDef)); return body; } } ``` -------------------------------- ### MotorJoint Example Implementation Source: https://docs.flame-engine.org/latest/bridge_packages/flame_forge2d/joints.html A complete Flame Forge2D example demonstrating the use of MotorJoint to make a ball spin around a center point. Tap the screen to change the rotation direction. Requires setup of Forge2DWorld, Ball, and Box components. ```dart import 'dart:ui'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/balls.dart'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boxes.dart'; import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class MotorJointExample extends Forge2DGame { static const description = ''' This example shows how to use a `MotorJoint`. The ball spins around the center point. Tap the screen to change the direction. '''; MotorJointExample() : super(gravity: Vector2.zero(), world: MotorJointWorld()); } class MotorJointWorld extends Forge2DWorld with TapCallbacks { late Ball ball; late MotorJoint joint; final motorSpeed = 1; bool clockWise = true; @override Future onLoad() async { super.onLoad(); final box = Box( startPosition: Vector2.zero(), width: 2, height: 1, bodyType: BodyType.static, ); add(box); ball = Ball(Vector2(0, -5)); add(ball); await Future.wait([ball.loaded, box.loaded]); joint = createMotorJoint(ball.body, box.body); add(JointRenderer(joint: joint)); } @override void onTapDown(TapDownEvent info) { super.onTapDown(info); clockWise = !clockWise; } MotorJoint createMotorJoint(Body first, Body second) { final motorJointDef = MotorJointDef() ..initialize(first, second) ..maxForce = 1000 ..maxTorque = 1000 ..correctionFactor = 0.1; final joint = MotorJoint(motorJointDef); createJoint(joint); return joint; } final linearOffset = Vector2.zero(); @override void update(double dt) { super.update(dt); var deltaOffset = motorSpeed * dt; if (clockWise) { deltaOffset = -deltaOffset; } final linearOffsetX = joint.getLinearOffset().x + deltaOffset; final linearOffsetY = joint.getLinearOffset().y + deltaOffset; linearOffset.setValues(linearOffsetX, linearOffsetY); final angularOffset = joint.getAngularOffset() + deltaOffset; joint.setLinearOffset(linearOffset); joint.setAngularOffset(angularOffset); } } class JointRenderer extends Component { JointRenderer({required this.joint}); final MotorJoint joint; @override void render(Canvas canvas) { canvas.drawLine( joint.anchorA.toOffset(), joint.anchorB.toOffset(), debugPaint, ); } } ``` -------------------------------- ### YarnProject Initialization and Parsing Source: https://docs.flame-engine.org/latest/other_modules/jenny/runtime/yarn_project.html Demonstrates how to initialize a YarnProject, link user-defined functions and commands, set the locale, and parse multiple yarn scripts. It also shows how to restore variables from a save-game storage. ```APIDOC ## YarnProject Initialization and Parsing ### Description This example shows the standard sequence of initializing a `YarnProject`, including linking user-defined functions and commands, setting the locale, parsing `.yarn` scripts, and restoring variables from storage. ### Method ```dart final yarn = YarnProject() ..functions.addFunction0('money', player.getMoney) ..commands.addCommand1('achievement', player.earnAchievement) ..parse(readFile('project.yarn')) ..parse(readFile('chapter1.yarn')) ..parse(readFile('chapter2.yarn')); ``` ### Properties Used - `functions`: To add user-defined functions. - `commands`: To add user-defined commands. - `parse`: To compile `.yarn` script text. ``` -------------------------------- ### Main Game Widget Setup Source: https://docs.flame-engine.org/latest/tutorials/space_shooter/step_2.html This is the entry point for the Flutter application. It uses `runApp` to display the `GameWidget`, which in turn renders the `SpaceShooterGame`. ```dart import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; void main() { runApp(GameWidget(game: SpaceShooterGame())); } class SpaceShooterGame extends FlameGame with PanDetector { late Player player; @override Future onLoad() async { player = Player(); add(player); } @override void onPanUpdate(DragUpdateInfo info) { player.move(info.delta.global); } } class Player extends SpriteComponent with HasGameReference { Player() : super( size: Vector2(100, 150), anchor: Anchor.center, ); @override Future onLoad() async { await super.onLoad(); sprite = await game.loadSprite('player-sprite.png'); position = game.size / 2; anchor = Anchor.center; } void move(Vector2 delta) { position.add(delta); } } ``` -------------------------------- ### Full PrismaticJoint Example with Limits and Motor Source: https://docs.flame-engine.org/latest/bridge_packages/flame_forge2d/joints.html Demonstrates a complete PrismaticJoint setup within a Flame Forge2D game, including enabling translation limits and a motor. This example allows dragging a box along a specified axis with bounds and a motor pulling it to a limit. ```dart import 'dart:ui'; import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boxes.dart'; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class PrismaticJointExample extends Forge2DGame { static const description = ''' This example shows how to use a `PrismaticJoint`. Drag the box along the specified axis, bound between lower and upper limits. Also, there's a motor enabled that's pulling the box to the lower limit. '''; final Vector2 anchor = Vector2.zero(); @override Future onLoad() async { super.onLoad(); final box = DraggableBox(startPosition: anchor, width: 6, height: 6); world.add(box); await Future.wait([box.loaded]); final joint = createJoint(box.body, anchor); world.add(JointRenderer(joint: joint, anchor: anchor)); } PrismaticJoint createJoint(Body box, Vector2 anchor) { final groundBody = world.createBody(BodyDef()); final prismaticJointDef = PrismaticJointDef() ..initialize( box, groundBody, anchor, Vector2(1, 0), ) ..enableLimit = true ..lowerTranslation = -20 ..upperTranslation = 20 ..enableMotor = true ..motorSpeed = 1 ..maxMotorForce = 100; final joint = PrismaticJoint(prismaticJointDef); world.createJoint(joint); return joint; } } class JointRenderer extends Component { JointRenderer({required this.joint, required this.anchor}); final PrismaticJoint joint; final Vector2 anchor; final Vector2 p1 = Vector2.zero(); final Vector2 p2 = Vector2.zero(); @override void render(Canvas canvas) { p1 ..setFrom(joint.getLocalAxisA()) ..scale(joint.getLowerLimit()) ..add(anchor); p2 ..setFrom(joint.getLocalAxisA()) ..scale(joint.getUpperLimit()) ..add(anchor); canvas.drawLine(p1.toOffset(), p2.toOffset(), debugPaint); } } ``` -------------------------------- ### ZigzagEffectController Example Source: https://docs.flame-engine.org/latest/flame/effects/effect_controllers.html Create simple alternating effects with ZigzagEffectController. It moves from 0 to 1, then to -1, and back to 0 over its period, ideal for oscillations starting from the center. ```dart final controller = ZigzagEffectController(period: 2); ``` -------------------------------- ### Build Documentation Site Source: https://docs.flame-engine.org/latest/development/documentation.html Renders the documentation site into HTML. This command needs to be re-run after document changes. ```bash melos doc-build ``` -------------------------------- ### Initialize Game Widget with Overlays Source: https://docs.flame-engine.org/latest/tutorials/platformer/step_7.html Sets up the main game widget, defining game factory, overlay builders, and initial active overlays. This is the entry point for the game. ```dart import 'package:flame/game.dart'; import 'package:flutter/material.dart'; import 'ember_quest.dart'; import 'overlays/game_over.dart'; import 'overlays/main_menu.dart'; void main() { runApp( GameWidget.controlled( gameFactory: EmberQuestGame.new, overlayBuilderMap: { 'MainMenu': (_, game) => MainMenu(game: game), 'GameOver': (_, game) => GameOver(game: game), }, initialActiveOverlays: const ['MainMenu'], ), ); } ``` -------------------------------- ### Serve and Auto-rebuild Documentation Source: https://docs.flame-engine.org/latest/development/documentation.html Automatically recompiles documentation on file changes and serves the site, opening it in the default browser. ```bash melos doc-serve ``` -------------------------------- ### Yarn File Structure Example Source: https://docs.flame-engine.org/latest/other_modules/jenny/language/language.html Demonstrates the basic structure of a .yarn file, including comments, tags, variable declarations, and a node definition. ```yarn // This is a comment // The line below, however, is a tag: # Chapter 1d <> <> // is this too much? title: Start --- // Node content === ``` -------------------------------- ### Example invocation of the StartQuest command Source: https://docs.flame-engine.org/latest/other_modules/jenny/runtime/command_storage.html Demonstrates how to invoke the `<>` command from a Yarn script, passing a quest ID and a quest name. The quest name is quoted to be treated as a single argument. ```yarn <> ``` -------------------------------- ### Custom Entity Collision Behavior Source: https://docs.flame-engine.org/latest/bridge_packages/flame_behaviors/collision-detection.html Define a custom collision behavior for your entity. This example shows how to specify the types of entities it can collide with and how to handle the start and end of collisions. ```dart class MyEntityCollisionBehavior extends CollisionBehavior { @override void onCollisionStart( Set intersectionPoints, MyCollidingEntity other, ) { // We are starting colliding with MyCollidingEntity } @override void onCollisionEnd(MyCollidingEntity other) { // We stopped colliding with MyCollidingEntity } } ``` -------------------------------- ### ScaleEffect.to Example Source: https://docs.flame-engine.org/latest/flame/effects/scale_effects.html Illustrates the use of `ScaleEffect.to` to set a component's scale to an absolute value. This is ideal for animations that require the component to reach a specific size, regardless of its starting scale. ```dart import 'package:doc_flame_examples/flower.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; class ScaleToEffectGame extends FlameGame { bool reverse = false; bool hold = false; @override Future onLoad() async { final flower = Flower( size: 60, position: canvasSize / 2, onTap: (flower) { if (hold) { return; } hold = true; flower.add( ScaleEffect.to( reverse ? Vector2.all(1) : Vector2.all(0.5), EffectController(duration: 0.5), onComplete: () => hold = false, ), ); reverse = !reverse; }, ); add(flower); } } ``` ```dart final effect = ScaleEffect.to( Vector2.all(0.5), EffectController(duration: 0.5), ); ``` -------------------------------- ### Initialize Game with Overlays Source: https://docs.flame-engine.org/latest/tutorials/platformer/step_7.html Configure the GameWidget to display initial overlays like the Main Menu and Game Over screen. ```dart void main() { runApp( GameWidget.controlled( gameFactory: EmberQuestGame.new, overlayBuilderMap: { 'MainMenu': (_, game) => MainMenu(game: game), 'GameOver': (_, game) => GameOver(game: game), }, initialActiveOverlays: const ['MainMenu'], ), ); } ```