思いついたときに使えるゲームエンジン
JavaScriptフルスクラッチの超簡易ゲームエンジンです。
まぁゲームエンジンなんて次元ではないですが、何かふと作りたくなったときなんかにパッと使えるといいなと思ってます。
See the Pen JavaScriptで超簡易ゲームエンジン作ったよ by いんわん (@inwan78) on CodePen.
ゲームエンジン部分のプログラム
const CORE = {
  setup: function(w, h){
    this.engine = new Engine(w, h);
  }
}
class Engine {
  constructor(w, h){
    const canvas = document.getElementById("canvas");
    canvas.width = w;
    canvas.height = h;
    canvas.style.backgroundColor = "#000000";
    CORE.canvas = canvas;
    CORE.ctx = canvas.getContext("2d");
    
    window.addEventListener('resize', () => {this.resizeCanvas();});
    this.resizeCanvas();  
  }
  _requestFrame(){
    this.update();
    requestAnimationFrame(()=>{this._requestFrame();});
  }
  resizeCanvas(){
    const canvas = CORE.canvas; 
    const canvasHeightRatio = canvas.height / canvas.width;
    const windowHeightRatio = window.innerHeight / window.innerWidth;
    
    let width;
    let height;
    if (windowHeightRatio > canvasHeightRatio) {
      width = window.innerWidth;
      height = window.innerWidth * (canvas.height / canvas.width);
    } else {
      width = window.innerHeight * (canvas.width / canvas.height);
      height = window.innerHeight;
    }
  
    canvas.style.width  = `${width}px`;
    canvas.style.height = `${height}px`;
    CORE.resolutionRatio = height / canvas.height;
  }
  preload(data){
    const length = Object.keys(data).length;
    let count = 0;
    const assets = [];
    for(let key in data) {
      assets[key] = new Image();
      assets[key].src = data[key];
      assets[key].onload = ()=>{
        if(++count == length){
          this.onload();
        }
      }
    }
    CORE.assets = assets;
  }
  clearCanvas(){
    CORE.ctx.clearRect(0, 0, CORE.canvas.width, CORE.canvas.height);
  }
  start(){
    this.init();
    requestAnimationFrame(()=>{this._requestFrame();});
  }
  onload(){}
  init(){}
  update(){}
}
サンプルに作ったゲーム
神経衰弱
See the Pen 神経衰弱作ったよ by inwan (@inwan78) on CodePen.
ライツアウト
See the Pen ライツアウトのゲーム作ったよ by inwan (@inwan78) on CodePen.
他にもあります
サンプルは他にもあります ▷ JavaScriptでゲーム作ろう!
解説もそっちにあるので気になる方は見てください('ω')ノ