0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScriptフルスクラッチでゲーム作る

Last updated at Posted at 2023-02-26

思いついたときに使えるゲームエンジン

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でゲーム作ろう!
解説もそっちにあるので気になる方は見てください('ω')ノ

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?