Bit Masking: Control Movement
Move widgets bit by bit
--
This example is provided as a FlutterPen and I won’t detail how to create a Flutter app. Instead, I will explain the code that manages the state as a decimal value using bitwise operators like AND, OR, or NOT.
Control movement
We’ll alter a state using the WASD keys (or the equivalent arrow keys ⇧⇦⇩⇨) and use that state to move an object on the screen.
That object will be a logo and its default position will be centered on the screen. The AnimatedPositioned widget will help us to move a bit more fluid, but the example would also work with a simple Positioned widget.
The state is kept in an integer and its default state equals 0. The binary representation where we need to store all 4 possible movement directions is 4 bit long: 0000
The mask values that we’ll use are as follows:
The following code snippets are written in Dart (Flutter’s core programming language).
We define some constants that will hold our raw key codes and their masks. These will help us identify which key was pressed or released.
static const int keyW = 119;
static const int keyA = 97;
static const int keyS = 115;
static const int keyD = 100;
static const int arrowUp = 4295426130;
static const int arrowLeft = 4295426128;
static const int arrowDown = 4295426129;
static const int arrowRight = 4295426127;
// decimal masks
static const int maskW = 8; // 1000
static const int maskA = 4; // 0100
static const int maskS = 2; // 0010
static const int maskD = 1; // 0001
We then listen to keyboard events on the entire screen (while it is in focus).
return RawKeyboardListener(
autofocus: true,
focusNode: FocusNode(),
onKey: (RawKeyEvent keyboardEvent) {
// on keyboard event…