Files
Luan Nico 8534a55740 docs: Add console with backtick on flame_console example (#3743)
Add console with backtick on flame_console example

This makes the example a bit more ergonomic to test changes to the
console by providing a key bind, backtick, for the console. This is also
much more in line with how actual games would use this feature instead
of a FAB (for example, on Bethesda games and many others, backtick
brings up the console), and in particular will teach how to properly
propagate events so both in-game keyboard handling _and_ the console
keyboard handlers can co-exist.
2025-10-06 12:50:46 +00:00

110 lines
2.8 KiB
Dart

import 'dart:async';
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame/events.dart';
import 'package:flame/game.dart';
import 'package:flame/palette.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
class MyGame extends FlameGame with HasKeyboardHandlerComponents {
@override
FutureOr<void> onLoad() async {
await super.onLoad();
world.addAll([
RectangleComponent(
position: Vector2(100, 0),
size: Vector2(100, 100),
paint: BasicPalette.white.paint(),
children: [
RectangleHitbox.relative(
Vector2.all(0.8),
parentSize: Vector2(100, 100),
),
SequenceEffect(
[
MoveEffect.by(
Vector2(-200, 0),
LinearEffectController(1),
),
MoveEffect.by(
Vector2(200, 0),
LinearEffectController(1),
),
],
infinite: true,
),
],
),
RectangleComponent(
position: Vector2(200, 100),
size: Vector2(100, 100),
paint: BasicPalette.white.paint(),
children: [
RectangleHitbox.relative(
Vector2.all(0.4),
parentSize: Vector2(100, 100),
),
SequenceEffect(
[
MoveEffect.by(
Vector2(-200, 0),
LinearEffectController(1),
),
MoveEffect.by(
Vector2(200, 0),
LinearEffectController(1),
),
],
infinite: true,
),
],
),
RectangleComponent(
position: Vector2(300, 200),
size: Vector2(100, 100),
paint: BasicPalette.white.paint(),
children: [
RectangleHitbox.relative(
Vector2.all(0.2),
parentSize: Vector2(100, 100),
),
SequenceEffect(
[
MoveEffect.by(
Vector2(-200, 0),
LinearEffectController(1),
),
MoveEffect.by(
Vector2(200, 0),
LinearEffectController(1),
),
],
infinite: true,
),
],
),
]);
}
@override
KeyEventResult onKeyEvent(
KeyEvent event,
Set<LogicalKeyboardKey> keysPressed,
) {
if (!overlays.isActive('console')) {
if (event is KeyDownEvent) {
final key = event.logicalKey;
if (key == LogicalKeyboardKey.backquote) {
overlays.add('console');
return KeyEventResult.handled;
}
}
}
return super.onKeyEvent(event, keysPressed);
}
}