Elements, Sprites & Animation
Learn how to represent game entities with GameElement, load spritesheets with SpriteManager,
play frame animations with AnimationPlayer, and apply transforms and parent hierarchies.
1. Creating a GameElement
Subclass GameElement and implement onUpdate(game, timeDelta) and onDraw(game, timeDelta).
Each element has isolated Config (position, size, rotation, flip, alpha, zIndex) and mutable State.
import { Game, GameElement } from 'maverick';
class Player extends GameElement {
onUpdate(_game: Game, timeDelta: number): void {
this.Config.pos!.x += this.State.speed * timeDelta;
}
onDraw(game: Game): void {
game.Viewport.drawElement(this);
}
}
// Inside Game.onReady():
const player = new Player(
this.Logger,
{
name: 'hero',
sprite: 'heroIdle',
pos: { x: 40, y: 120 },
rotation: 0,
flipX: false,
alpha: 1,
zIndex: 1,
},
{ speed: 120 }
);
this.Elements.add(player);
2. Spritesheets & Preloading
Register image files with Sprites.addSource(id, path), await readiness with await Sprites.preload(),
and slice sub-rectangles with Sprites.addSprite(spriteId, sourceId, config).
this.Sprites.addSource('sheet', './assets/characters.png');
await this.Sprites.preload('sheet'); // 'idle' | 'loading' | 'ready' | 'error'
this.Sprites.addSprite('heroWalk1', 'sheet', {
source: 'sheet',
spriteCoordinates: { x: 0, y: 0, width: 32, height: 32 },
renderOffset: { x: -16, y: -16 },
scale: 2,
});
3. Frame Animation (AnimationPlayer)
Use AnimationPlayer to switch between sprite frames at a fixed FPS, with looping or one-shot completion callbacks.
import { AnimationPlayer } from 'maverick';
const anim = new AnimationPlayer();
anim.addClip({ id: 'walk', frames: ['heroWalk1', 'heroWalk2'], fps: 8, loop: true });
anim.addClip({ id: 'attack', frames: ['heroAtk1', 'heroAtk2'], fps: 12, loop: false });
anim.onComplete = (clipId) => {
if (clipId === 'attack') anim.play('walk');
};
anim.play('walk');
// Inside element.onUpdate(game, dt):
anim.update(dt);
this.Config.sprite = anim.CurrentFrame ?? this.Config.sprite;
4. Parent Hierarchy
Set parent: 'hero' on a child element (such as a weapon or shadow) and resolve its combined world coordinates
with Elements.getWorldPosition(child) (cycle-safe).