シンプルゲーム(重力加速度)

前回javascriptの重力加速度を参考にシンプルなゲームを作成しました。

マウスを押すと対象物が上に上がり、マウスを離すと対象物が下がるというシンプルなものです

キャンバスの表示内容を説明する代替テキストです。

以下ソース

let ctx,
        isFlying = false,
        timer;
      let posY = 300,
        offset = 0,
        speed = 10,
        velocityY = -20,
        accelY = 5;

      function init() {
        ctx = document.getElementById("viewer").getContext("2d");
        ctx.font = "24px sans-serif";
        onmousedown = function () {
          isFlying = true;
        };
        onmouseup = function () {
          isFlying = false;
        };
        timer = setInterval(tick, 100);
      }

      function tick() {
        velocityY += isFlying ? -accelY : accelY;
        posY += velocityY;
        offset += speed;
        if (offset % 100 == 0) {
          speed += 2;
        }
        paint();
      }

      function paint() {
        ctx.fillStyle = "green";
        ctx.fillRect(0, 0, 600, 600);

        ctx.fillStyle = "brown";
        ctx.beginPath();
        ctx.moveTo(0, 0);
        for (let i = 0; i <= 600; i += 10) {
          let up = 200 + Math.sin(((i + offset) * Math.PI) / 360) * 80;
          ctx.lineTo(i, up);
          if (i === 10 && posY < up) {
            clearInterval(timer);
          }
        }
        ctx.lineTo(600, 0);
        ctx.fill();

        ctx.beginPath();
        ctx.moveTo(0, 600);
        for (let i = 0; i <= 600; i += 10) {
          let down = 400 + Math.sin(((i + offset) * Math.PI) / 340) * 80;
          ctx.lineTo(i, down);
          if (i === 10 && posY + 10 > down) {
            clearInterval(timer);
          }
        }
        ctx.lineTo(620, 600);
        ctx.fill();

        ctx.fillStyle = "white";
        ctx.fillRect(10, posY, 10, 10);
        ctx.fillText(offset, 500, 50);
      }
      window.onload = init;    
    

Enjoy!!

utthi_fumi is javascript programmer.