Move object with keyboard
by bc_rikko
HTML
<div>
<canvas id="app" width="640" height="360"></canvas>
</div>
<button id="start">start</button>
<button id="stop">stop</button>
CSS
canvas {
background-color: white;
}
JavaScript
class Game {
constructor(opt) {
this._canvas = opt.canvas;
this._ctx = this._canvas.getContext('2d');
this._assets = opt.assets;
this._loadedAssets = {};
this._fps = opt.fps || 30;
this._timer;
this._items = [];
this._keyboard = '';
this._setEventListener();
}
async start() {
await this._loadAssets();
this._timer = setInterval(() => {
this._render();
}, 1000 / this._fps);
}
stop() {
clearInterval(this._timer);
}
async _loadAssets() {
const promises = Object.keys(this._assets).map(asset => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => { resolve(); }
img.onerror = err => { reject(err); }
img.src = this._assets[asset];
this._loadedAssets[asset] = img;
});
});
return Promise.all(promises);
}
_render() {
this._ctx.clearRect(0, 0, this._canvas.clientWidth, this._canvas.clientHeight);
this._items.forEach(a => {
a.draw(this._ctx, this._loadedAssets);
a.update(this._keyboard);
})
}
_setEventListener() {
window.addEventListener('keydown', e => { this._keyboard = e.key });
window.addEventListener('keyup', e => { this._keyboard = '' });
}
add(item) {
this._items.push(item);
}
remove(item) {
const idx = this._items.find(a => a === item);
this._items.splice(idx, 1);
}
}
class Player {
constructor(opt = {}) {
this.x = opt.x || 0;
this.y = opt.y || 0;
this.w = opt.w || 64;
this.h = opt.h || 64;
this.src = opt.src;
}
draw(ctx, assets) {
if (assets[this.src]) {
ctx.drawImage(assets[this.src], this.x, this.y, this.w, this.h);
} else {
ctx.fillRect(this.x, this.y, this.w, this.h);
}
}
update(keyboard) {
// ここで動作を定義する
switch (keyboard) {
case 'ArrowUp':
this.y -= 5;
break;
case 'ArrowDown':
this.y += 5;
break;
case...