Last active
July 6, 2020 20:35
-
-
Save mattdesl/70dfbf79132e9ed78fb8ca9cf8db9ef3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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