Last active
July 9, 2022 17:48
-
-
Save 3mcd/f40ae79f678810050ee498d4ab6740cb to your computer and use it in GitHub Desktop.
Javelin 1.0 docs box example
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 { | |
after, | |
App, | |
Component, | |
Resource, | |
useKeyboard, | |
useQuery, | |
useResource, | |
World, | |
} from "@javelin/ecs" | |
const Context2D = Resource.create<CanvasRenderingContext2D>() | |
const Position = Component.create<{x: number; y: number}>() | |
const Color = Component.create<{value: string}>() | |
const Box = Position.and(Color) | |
function createBox(world: World) { | |
const box = world.create() | |
world.add(box, Box, {x: 0, y: 0}, {value: "#ff0000"}) | |
} | |
function moveBox() { | |
const keys = useKeyboard() | |
const boxes = useQuery(Box) | |
const moveX = Number(keys.poll("ArrowRight")) - Number(keys.poll("ArrowLeft")) | |
const moveY = Number(keys.poll("ArrowDown")) - Number(keys.poll("ArrowUp")) | |
boxes.forEach((entity, position) => { | |
position.x += moveX | |
position.y += moveY | |
}) | |
} | |
function clearCanvas() { | |
const context = useResource(Context2D) | |
context.clearRect(0, 0, 300, 150) // default canvas width/height | |
} | |
function drawBox() { | |
const context = useResource(Context2D) | |
const boxes = useQuery(Box) | |
boxes.forEach((entity, {x, y}, {value: color}) => { | |
context.fillStyle = color | |
context.fillRect(x, y, 1, 1) | |
}) | |
} | |
const context2d = document.querySelector("canvas")!.getContext("2d") | |
const app = App.create() | |
.addResource(Context2D, context2d) | |
.addStartupSystem(createBox) | |
.addSystem(moveBox) | |
.addSystemToStage(App.PostUpdate, clearCanvas) | |
.addSystemToStage(App.PostUpdate, drawBox, after(clearCanvas)) | |
function loop() { | |
app.step() | |
requestAnimationFrame(loop) | |
} | |
loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment