Reading time: 2 minutes
In this tutorial, I’m going to explain how you can add colors to BodyComponent elements in Flame Engine (https://examples.flame-engine.org).
In this example, I’m going to add a BodyComponent representing a blue bar.
class BlueBar extends BodyComponent { // Passed parameters final double positionX; final double positionY; final double angularVelocity; // Constructor BlueBar(this.positionX, this.positionY, this.angularVelocity) { } @override Body createBody() { final bodyDef = BodyDef( position: Vector2(positionX, positionY), type: BodyType.kinematic, ); // Shape with color final shape = PolygonShape()..setAsBoxXY(.15, 1.25); final fixtureDef = FixtureDef(shape); return world.createBody(bodyDef) ..createFixture(fixtureDef) ..angularVelocity = radians(angularVelocity); } }
This creates the following figure on the screen:
To apply a color, we’ll use the Flame Engine package: flame/palette.dart
import 'package:flame/palette.dart';
Once imported, we can create the desired color:
final Paint blue = BasicPalette.blue.paint();
In this case, we use the color blue.
If we want to assign it to the element, we just need to change the color variable in its constructor (the color variable is already present by default in the BodyComponent/Component).
BlueBar(this.positionX, this.positionY, this.angularVelocity) { paint = blue; }
This is the resulting code:
class BlueBar extends BodyComponent { // Passed parameters final double positionX; final double positionY; final double angularVelocity; final Paint blue = BasicPalette.blue.paint(); // Constructor BlueBar(this.positionX, this.positionY, this.angularVelocity) { paint = blue; } @override Body createBody() { final bodyDef = BodyDef( position: Vector2(positionX, positionY), type: BodyType.kinematic, ); // Shape with color final shape = PolygonShape()..setAsBoxXY(.15, 1.25); Paint randomPaint() => PaintExtension.random(withAlpha: 0.9, base: 100); //final fixtureDef = FixtureDef(shape); final fixtureDef = FixtureDef( shape, restitution: 0.8, density: 1.0, friction: 0.4, ); return world.createBody(bodyDef) ..createFixture(fixtureDef) ..angularVelocity = radians(angularVelocity); } }
And this is how it appears on the screen: