npm install -g create-react-app
create-react-app zelda
npm start
<!-- index.html -->
<body>
<canvas id="game"></canvas>
</body>
// index.js
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const initialState = {
playerHasSword: false,
ganonIsDead: false,
player: {
position: [width / 2, 20],
facing: 'down',
width: 16,
height: 24,
},
// ...
};
function update(prevState, dt) {
const newState = {...prevState};
if (keysDown.has(keyCodes.UP_ARROW)) {
newState.player.position[1] -= playerSpeed * dt;
newState.player.facing = 'up';
}
if (keysDown.has(keyCodes.DOWN_ARROW)) {
newState.player.position[1] += playerSpeed * dt;
newState.player.facing = 'down';
}
// (you can probably guess the code for left & right)
// ...
return newState;
}
function update(prevState, dt) {
// ...
if (colliding(newState.player, newState.sword)) {
newState.playerHasSword = true;
}
if (colliding(newState.player, newState.ganon)) {
if (newState.playerHasSword) {
newState.ganonIsDead = true;
}
}
}
export default function colliding(rect1, rect2) {
return (
rect1.position[0] < rect2.position[0] + rect2.width &&
rect1.position[0] + rect1.width > rect2.position[0] &&
rect1.position[1] < rect2.position[1] + rect2.height &&
rect1.height + rect1.position[1] > rect2.position[1]
);
}
const images = {
'zelda-up': require('../sprites/zelda-up.png'),
// ...
};
function draw(ctx, state) {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, width, height);
// render player
const spritePath = images[`zelda-${state.player.facing}`];
const image = new Image(spritePath);
ctx.drawImage(
ctx,
image,
state.player.position[0],
state.player.position[1]
);
// ... draw ganon, sword ...
}
function runLoop(
prevState = initialState, prevTime = Date.now()) {
requestAnimationFrame(() => {
const currentTime = Date.now();
const dt = currentTime - prevTime;
const newState = update(prevState, dt / 1000);
draw(ctx, newState);
runLoop(newState, currentTime);
});
}
runLoop();
Physics? `npm install p2.js`
Tricky collision detection? `npm install sat`
(and so many, many other tools)