flutter spritewidget
spritewidget is a toolkit for building complex, high-performance animations and 2d games with flutter. your sprite renders tree lives inside a widget that mixes seamlessly with other flutter and material widgets. you can use spritewidget to create anything from an animated icon to a full-fledged game.
this guide assumes a basic knowledge of flutter and dart. get support by posting a question tagged spritewidget on stackoverflow.
you can find examples in the example directory, or check out the complete space blast game.
adding spritewidget to your project
spritewidget is available as a standard package. just add it as a dependency to your pubspec.yaml and you are good to go.
dependencies:
flutter:
sdk: flutter
spritewidget:
creating a spritewidget
the first thing you need to do to use spritewidget is to setup a root node that is used to draw it’s contents. any sprite nodes that you add to the root node will be rendered by the spritewidget. typically, your root node is part of your app’s state. this is an example of how you can setup a custom stateful widget with a spritewidget:
import 'package:flutter/material.dart';
import 'package:spritewidget/spritewidget.dart';
class mywidget extends statefulwidget {
@override
mywidgetstate createstate() => new mywidgetstate();
}
class mywidgetstate extends state<mywidget> {
nodewithsize rootnode;
@override
void initstate() {
super.initstate();
rootnode = new nodewithsize(const size(1024.0, 1024.0));
}
@override
widget build(buildcontext context) {
return new spritewidget(rootnode);
}
}
the root node that you provide the spritewidget is a nodewithsize, the size of the root node defines the coordinate system used by the spritewidget. by default the spritewidget uses letterboxing to display its contents. this means that the size that you give the root node will determine how the spritewidget’s contents will be scaled to fit. if it doesn’t fit perfectly in the area of the widget, either its top and bottom or the left and right side will be trimmed. you can optionally pass in a parameter to the spritewidget for other scaling options depending on your needs.
when you have added the spritewidget to your app’s build method it will automatically start running animations and handling user input. there is no need for any other extra setup.
adding objects to your node graph
your spritewidget manages a node graph, the root node is the nodewithsize that is passed in to the spritewidget when it’s created. to render sprites, particles systems, or any other objects simply add them to the node graph.
each node in the node graph has a transform. the transform is inherited by its children, this makes it possible to build more complex structures by grouping objects together as children to a node and then manipulating the parent node. for example the following code creates a car sprite with two wheels attached to it. the car is added to the root node.
sprite car = new sprite.fromimage(carimage);
sprite frontwheel = new sprite.fromimage(wheelimage);
sprite rearwheel = new sprite.fromimage(wheelimage);
frontwheel.position = const offset(100, 50);
rearwheel.position = const offset(-100, 50);
car.addchild(frontwheel);
car.addchild(rearwheel);
rootnode.addchild(car);
you can manipulate the transform by setting the position, rotation, scale, and skew properties.
sprites, textures, and sprite sheets
to load image resources, the easiest way is to use the imagemap
class. the imagemap
can load one or multiple images at once.
the image
class isn’t automatically imported through flutter/material, so you may need to add an import at the top of your file.
import 'dart:ui' as ui show image;
now you can load images using the imagemap
. note that the loading methods are asynchronous, so this example code will need to go in an asynch method. for a full example of loading images see the weather demo.
imagemap images = new imagemap(rootbundle);
// load a single image
ui.image image = await images.loadimage('assets/my_image.png');
// load multiple images
await images.load(<string>[
'assets/image_0.png',
'assets/image_1.png',
'assets/image_2.png',
]);
// access a loaded image from the imagemap
image = images['assets/image_0.png'];
the most common node type is the sprite node. a sprite simply draws an image to the screen. sprites can be drawn from image objects or spritetexture objects. a texture is a part of an image. using a spritesheet you can pack several texture elements within a single image. this saves space in the device’s gpu memory and also make drawing faster. currently spritewidget supports sprite sheets in json format and produced with a tool such as texturepacker. it’s uncommon to manually edit the sprite sheet files. you can create a spritesheet with a definition in json and an image:
spritesheet sprites = new spritesheet(myimage, jsoncode);
spritetexture texture = sprites['texture.png'];
the frame cycle
each time a new frame is rendered to screen spritewidget will perform a number of actions. sometimes when creating more advanced interactive animations or games, the order in which these actions are performed may matter.
this is the order things will happen:
- handle input events
- run animation actions
- call update functions on nodes
- apply constraints
- render the frame to screen
read more about each of the different phases below.
handling user input
you can subclass any node type to handle touches. to receive touches, you need to set the userinteractionenabled property to true and override the handleevent method. if the node you are subclassing doesn’t have a size, you will also need to override the ispointinside method.
class eventhandlingnode extends nodewithsize {
eventhandlingnode(size size) : super(size) {
userinteractionenabled = true;
}
@override handleevent(spriteboxevent event) {
if (event.type == pointerdownevent)
...
else if (event.type == pointermoveevent)
...
return true;
}
}
if you want your node to receive multiple touches, set the handlemultiplepointers property to true. each touch down or dragged touch will generate a separate call to the handleevent method, you can distinguish each touch by its pointer property.
animating using actions
spritewidget provides easy to use functions for animating nodes through actions. you can combine simple action blocks to create more complex animations.
to execute an action animation you first build the action itself, then pass it to the run method of a nodes action manager (see the tweens section below for an example).
tweens
tweens are the simplest building block for creating an animation. it will interpolate a value or property over a specified time period. you provide the actiontween class with a setter function, its start and end value, and the duration for the tween.
after creating a tween, execute it by running it through a node’s action manager.
node mynode = new node();
actiontween mytween = new actiontween<offset> (
(a) => mynode.position = a,
offset.zero,
const offset(100.0, 0.0),
1.0
);
mynode.actions.run(mytween);
you can animate values of different types, such as floats, points, rectangles, and even colors. you can also optionally provide the actiontween class with an easing function.
sequences
when you need to play two or more actions in a sequence, use the actionsequence class:
actionsequence sequence = new actionsequence([
firstaction,
middleaction,
lastaction
]);
groups
use actiongroup to play actions in parallel:
actiongroup group = new actiongroup([
action0,
action1
]);
repeat
you can loop any action, either a fixed number of times, or until the end of times:
actionrepeat repeat = new actionrepeat(loopedaction, 5);
actionrepeatforever longloop = new actionrepeatforever(loopedaction);
composition
it’s possible to create more complex actions by composing them in any way:
actionsequence complexaction = new actionsequence([
new actionrepeat(myloop, 2),
new actiongroup([
action0,
action1
])
]);
handle update events
each frame, update events are sent to each node in the current node tree. override the update method to manually do animations or to perform game logic.
mynode extends node {
@override
update(double dt) {
// move the node at a constant speed
position += new offset(dt * 1.0, 0.0);
}
}
defining constraints
constraints are used to constrain properties of nodes. they can be used to position nodes relative other nodes, or adjust the rotation or scale. you can apply more than one constraint to a single node.
for example, you can use a constraint to make a node follow another node at a specific distance with a specified dampening. the dampening will smoothen out the following node’s movement.
followingnode.constraints = [
new constraintpositiontonode(
targetnode,
offset: const offset(0.0, 100.0),
dampening: 0.5
)
];
constraints are applied at the end of the frame cycle. if you need them to be applied at any other time, you can directly call the applyconstraints method of a node object.
perform custom drawing
spritewidget provides a default set of drawing primitives, but there are cases where you may want to perform custom drawing. to do this you will need to subclass either the node or nodewithsize class and override the paint method:
class redcircle extends node {
redcircle(this.radius);
double radius;
@override
void paint(canvas canvas) {
canvas.drawcircle(
offset.zero,
radius,
new paint()..color = const color(0xffff0000)
);
}
}
if you are overriding a nodewithsize you may want to call applytransformforpivot before starting drawing to account for the node’s pivot point. after the call the coordinate system is setup so you can perform drawing starting at origo to the size of the node.
@override
void paint(canvas canvas) {
applytransformforpivot(canvas);
canvas.drawrect(
new rect.fromltwh(0.0, 0.0, size.width, size.height),
mypaint
);
}
add effects using particle systems
particle systems are great for creating effects such as rain, smoke, or fire. it’s easy to setup a particle system, but there are very many properties that can be tweaked. the best way of to get a feel for how they work is to simply play around with the them.
this is an example of how a particle system can be created, configured, and added to the scene:
particlesystem particles = new particlesystem(
particletexture,
posvar: const point(100, 100.0),
startsize: 1.0,
startsizevar: 0.5,
endsize: 2.0,
endsizevar: 1.0,
life: 1.5 * distance,
lifevar: 1.0 * distance
);
rootnode.addchild(particles);
Comments are closed.