onLoad method
Late initialization method for Component
.
Usually, this method is the main place where you initialize your component. This has several advantages over the traditional constructor:
- this method can be
async
; - it is invoked when the size of the game canvas is already known.
If your loading logic requires knowing the size of the game canvas, then
add HasGameRef
mixin and then query game.size
or
game.canvasSize
.
The default implementation returns null
, indicating that there is no
need to await anything. When overriding this method, you have a choice
whether to create a regular or async function.
If you need an asynchronous onLoad, make your override return
non-nullable Future<void>
:
@override
Future<void> onLoad() async {
// your code here
}
Alternatively, if your onLoad function doesn't use any await
ing, then
you can declare it as a regular method returning void
:
@override
void onLoad() {
// your code here
}
The engine ensures that this method will be called exactly once during
the lifetime of the Component
object. Do not call this method manually.
Implementation
@override
Future<void> onLoad() async {
/// first add the canvas map
world.add(CanvasMap());
/// add the focus point so cam will be pointing in the center
world.add(focusPoint = FocusPointImpl());
/// add bound to the Canvas so camera cannot move beyond the size
camera.setBounds(Rectangle.fromPoints(
Vector2(0, 0), Vector2(CanvasMap.size, CanvasMap.size)));
/// camera should fallow the focusPoint focus point moves
/// int canvas for scroll and for zoom
camera.follow(
focusPoint,
);
/// render the nodes in the screen
void renderData() {
double i = 0;
double j = 0;
/// render the nodes in the screen
graphDataStructure.generateItem((node) {
double nodei = i;
double nodej = j;
world.add(
NodeModule(
nodeSize: Vector2((nodeSize + (nodePadding * 2)),
(nodeSize + (nodePadding * 2))),
nodePosition: Vector2(nodej, nodei),
nodePadding: nodePadding,
graphNode: node,
nodeImageSize: nodeSize,
graphDataStructure: graphDataStructure),
);
if (j < CanvasMap.size - (nodeSize + (nodePadding * 2))) {
j = j + (nodeSize + (nodePadding * 2));
} else {
i = i + (nodeSize + (nodePadding * 2));
j = 0;
}
});
}
/// once node is rendered then render the lines
void addLines() {
graphDataStructure.generateItem((node) {
world.add(LineDrawer(graphNode: node));
});
}
/// render the nodes in the screen
renderData();
/// once node is rendered then render the lines
addLines();
}