17.7 Adding Keyboard input
import 'dart:async' ;
import 'package:flame/flame.dart' ;
import 'package:flame/game.dart' ;
import 'package:flame/input.dart' ; // Keyboard
import 'package:flutter/services.dart' ; // Keyboard
import 'package:flame/components.dart' ;
import 'package:flutter/material.dart' ;
void main () async {
WidgetsFlutterBinding .ensureInitialized ();
await Flame .device.setPortrait ();
final shapeGame = ShapesExample ();
runApp (GameWidget (game: shapeGame));
}
// Global key direction
double xDelta = 0 ;
class ShapesExample extends FlameGame
with KeyboardEvents , HasCollisionDetection {
@override
Future <void > onLoad () async {
super .onLoad ();
add (RectComponent (size[0 ], size[1 ]));
}
// @override
// void update(double dt) {
// super.update(dt);
// }
// @override
// void render(Canvas canvas) {
// super.render(canvas);
// }
@override
KeyEventResult onKeyEvent (
RawKeyEvent event, Set <LogicalKeyboardKey > keysPressed) {
final isKeyDown = event is RawKeyDownEvent ;
// final isDirectionKey = keysPressed.contains(LogicalKeyboardKey.keyA);
if (isKeyDown && event.logicalKey == LogicalKeyboardKey .keyA) {
xDelta = isKeyDown ? - 1 : 0 ;
}
if (isKeyDown && event.logicalKey == LogicalKeyboardKey .keyD) {
xDelta = isKeyDown ? 1 : 0 ;
}
if (isKeyDown && event.logicalKey == LogicalKeyboardKey .keyW) {
xDelta = isKeyDown ? - 1 : 0 ;
}
if (isKeyDown && event.logicalKey == LogicalKeyboardKey .keyS) {
xDelta = isKeyDown ? 1 : 0 ;
}
return super .onKeyEvent (event, keysPressed);
}
}
// Add a [Color] Rect on screen
class RectComponent extends PositionComponent {
final double screenWidth;
final double screenHeight;
static double xRectWidth = 50 ;
static double yRectHeight = 50 ;
double xStartPosition = 0 ;
double yStartPosition = 0 ;
int rectDirection = 1 ;
final paint = Paint ()
..color = Colors .white
..strokeWidth = 4 ;
RectComponent (this .screenWidth, this .screenHeight);
@override
Future <void > onLoad () async {
super .onLoad ();
xStartPosition = screenWidth / 2 ;
yStartPosition = screenHeight / 2 ;
}
@override
void update (double dt) {
super .update (dt);
// Going Left
if (xDelta == - 1 ) {
// Check the screen boundary
if (xStartPosition >= 0 ) {
xStartPosition -= 5 ;
}
// ignore: avoid_print
print ('Go Left' );
xDelta = 0 ;
} else if (xDelta == 1 ) {
// Check the screen boundary
if (xStartPosition <= screenWidth) {
xStartPosition += 5 ;
}
// ignore: avoid_print
print ('Go Right' );
xDelta = 0 ;
}
}
@override
void render (Canvas canvas) {
super .render (canvas);
// xStartPos, yStartPos, xRectWidth, yRectHeight
canvas.drawRect (
Rect .fromLTWH (xStartPosition, yStartPosition, xRectWidth, yRectHeight),
paint);
}
}