Skip to content

Instantly share code, notes, and snippets.

@fritzy
Created August 7, 2020 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fritzy/1b676b9cea914dc521f467c688ed172e to your computer and use it in GitHub Desktop.
Save fritzy/1b676b9cea914dc521f467c688ed172e to your computer and use it in GitHub Desktop.
ApeECS Example of Managing Sprites from Pixi.js
const ApeECS = require('ApeECS');
const Pixi = require('pixi.js');
const world = new ApeECS.World();
class Sprite extends ApeECS.Component {
static properties = {
x: 0,
y: 0,
layer: '',
texturePath: '',
sprite: null
};
static serializeFields = ['x', 'y', 'texturePath'];
get x() {
if (this.sprite) {
return this.sprite.position.x;
}
return this._meta.values.x;
}
set x(value) {
if (this.sprite) {
this.sprite.position.x = value;
}
this._meta.values.x = value;
return true;
}
get y() {
if (this.sprite) {
return this.sprite.position.y;
}
return this._meta.values.y;
}
set y(value) {
if (this.sprite) {
this.sprite.position.y = value;
}
this._meta.values.y = value;
return true;
}
}
class Layer extends ApeECS.Component {
static properties {
container = null;
}
}
world.registerComponent(Sprite);
world.registrerComponent(Layer);
const groundLayer = new Pixi.Container();
//assume we have a pixiGame value that we can add containers to
pixiGame.addChild(groundLayer);
const characterLayer = new Pixi.Container();
pixiGame.addChild(characterLayer);
world.createEntity({
id: 'level',
components: [
{
type: 'Layer',
lookup: 'groundLayer',
container: groundLayer
},
{
type: 'Layer',
lookup: 'characterLayer',
container: characterLayer
}
]
});
// .. loading a level...
// you'd probably load the file some other way
// maybe in a system somewhere
const levelJson = require('saveGame.json');
world.createEntities(levelJson);
const level = world.getEntity('level');
// this might be in a system that just checks for new sprites
const newSpritesQuery = world.createQuery().fromAll('Sprite', 'Uninitialized');
const newSprites = newSpritesQuery.execute();
for (const sprite of newSprites) {
const pSprite = new Pixi.Sprite(sprite.texturePath);
const pSprite.position.set(sprite.x, sprite.y);
sprite.sprite = pSprite;
level[sprite.layer].container.add(pSprite);
sprite.removeTag('Uninitialized');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment