Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Last active July 6, 2020 20:35
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 mattdesl/70dfbf79132e9ed78fb8ca9cf8db9ef3 to your computer and use it in GitHub Desktop.
Save mattdesl/70dfbf79132e9ed78fb8ca9cf8db9ef3 to your computer and use it in GitHub Desktop.
import { Types, Component, System, World, TagComponent } from 'ecsy';
// An entity that, when clicked,
// will randomly change its color
// and play a sound
class Element extends Component {}
Element.schema = {
value: { type: Types.Ref }
};
class Appearance extends Component {}
Appearance.schema = {
color: { type: Types.String }
};
class ChangeColorOnClick extends Component {}
ChangeColorOnClick.schema = {
color: { type: Types.String }
};
class AppearanceSystem extends System {
execute () {
this.queries.entities.results.forEach(e => {
const el = e.getComponent(Element).value;
const color = e.getComponent(Appearance).color;
el.style.backgroundColor = color;
});
}
}
AppearanceSystem.queries = {
entities: {
components: [ Element, Appearance ]
}
};
class ChangeColorOnClickSystem extends System {
init () {
}
execute () {
// This should change color on mouse click
// how ???
}
}
ChangeColorOnClickSystem.queries = {
entities: {
components: [ ChangeColorOnClick, Appearance ],
}
}
const world = new World();
world.registerSystem(AppearanceSystem);
world.registerSystem(ChangeColorOnClickSystem);
world.registerComponent(Element);
world.registerComponent(Appearance);
world.registerComponent(ChangeColorOnClick);
const div = document.createElement('div');
Object.assign(div.style, {
width: '250px',
height: '250px',
cursor: 'pointer'
});
document.body.appendChild(div);
world.createEntity()
.addComponent(Element, { value: div })
.addComponent(Appearance, { color: 'blue' })
.addComponent(ChangeColorOnClick, { color: 'red' })
let lastTime = performance.now();
function run () {
// Compute delta and elapsed time
let time = performance.now();
let delta = time - lastTime;
world.execute(delta, time);
lastTime = time;
requestAnimationFrame(run);
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment