ToroVerse

作品:横スクロールアクション

この回でできるようになること

走って、跳んで、足場を渡り、敵を踏み、コインを集めて、ゴールを目指す。横スクロールのアクションゲームを、作ります。ステージは、マス目で組み立てます。重力、ジャンプ、ブロックとの当たり、カメラ、敵。たくさんの仕組みを、役割ごとに、クラスと関数に分けて、1つのゲームに、組み上げます。

sketch.js
const TILE = 40;
const ROWS = 10;
const COLS = 80;
const GRAVITY = 0.6;

let walkImage;
let enemyImage;

let scene = 'title';
let message = '';
let stage = [];
let player;
let enemies = [];
let cameraX = 0;
let coins = 0;
let lives = 3;

async function setup() {
  createCanvas(400, 400);
  walkImage = await loadImage('walk.png');
  enemyImage = await loadImage('enemies.png');
  makeStage();
}

function draw() {
  background(150, 200, 255);

  if (scene === 'title') {
    drawWorld();
    drawTitle();
  } else if (scene === 'play') {
    updateGame();
    drawWorld();
    drawStatus();
  } else if (scene === 'result') {
    drawWorld();
    drawStatus();
    drawResult();
  }
}

// ---------- ステージ ----------

// row 行目の、colStart 列目から colEnd 列目までを、value にする
function fillTiles(row, colStart, colEnd, value) {
  for (let col = colStart; col <= colEnd; col++) {
    stage[row][col] = value;
  }
}

// ステージを作る。0:何もない 1:ブロック 2:コイン 3:ゴール
function makeStage() {
  for (let row = 0; row < ROWS; row++) {
    stage[row] = [];
    for (let col = 0; col < COLS; col++) {
      stage[row][col] = 0;
    }
  }

  // 地面と、穴
  fillTiles(8, 0, COLS - 1, 1);
  fillTiles(9, 0, COLS - 1, 1);
  fillTiles(8, 14, 16, 0);
  fillTiles(9, 14, 16, 0);
  fillTiles(8, 33, 36, 0);
  fillTiles(9, 33, 36, 0);
  fillTiles(8, 55, 57, 0);
  fillTiles(9, 55, 57, 0);

  // 足場
  fillTiles(6, 7, 9, 1);
  fillTiles(5, 20, 23, 1);
  fillTiles(3, 25, 27, 1);
  fillTiles(6, 34, 35, 1);
  fillTiles(7, 42, 42, 1);
  fillTiles(6, 43, 43, 1);
  fillTiles(5, 44, 48, 1);
  fillTiles(5, 61, 63, 1);
  fillTiles(3, 66, 68, 1);

  // コイン
  fillTiles(5, 7, 9, 2);
  fillTiles(4, 20, 23, 2);
  fillTiles(2, 25, 27, 2);
  fillTiles(4, 45, 47, 2);
  fillTiles(2, 66, 68, 2);
  fillTiles(6, 15, 15, 2);

  // ゴール
  stage[7][76] = 3;

  enemies = [];
  enemies.push(new Walker(11 * TILE, 7 * TILE));
  enemies.push(new Walker(21 * TILE, 4 * TILE));
  enemies.push(new Walker(29 * TILE, 7 * TILE));
  enemies.push(new Hopper(40 * TILE, 7 * TILE));
  enemies.push(new Walker(46 * TILE, 4 * TILE));
  enemies.push(new Hopper(52 * TILE, 7 * TILE));
  enemies.push(new Walker(62 * TILE, 4 * TILE));
  enemies.push(new Walker(70 * TILE, 7 * TILE));
}

// 画面上の座標 (px, py) にあるマスの、値を返す
function tileAt(px, py) {
  let col = floor(px / TILE);
  let row = floor(py / TILE);
  if (col < 0 || col >= COLS) {
    return 1;
  }
  if (row < 0 || row >= ROWS) {
    return 0;
  }
  return stage[row][col];
}

function isSolid(px, py) {
  return tileAt(px, py) === 1;
}

// ---------- ゲームの進行 ----------

function startGame() {
  makeStage();
  player = new Player(60, 200);
  cameraX = 0;
  coins = 0;
  lives = 3;
}

function updateGame() {
  player.update();

  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();

    if (player.overlaps(enemy)) {
      if (player.vy > 0 && player.y + player.h < enemy.y + enemy.h * 0.6) {
        // 上から踏んだ。敵を消して、小さく跳ねる
        enemies.splice(i, 1);
        player.vy = -8;
      } else {
        loseLife();
      }
    }
  }

  // コインと、ゴール。自機の中心がある、マスを調べる
  let cx = player.x + player.w / 2;
  let cy = player.y + player.h / 2;
  let here = tileAt(cx, cy);
  if (here === 2) {
    stage[floor(cy / TILE)][floor(cx / TILE)] = 0;
    coins += 1;
  }
  if (here === 3) {
    message = 'ゴール!';
    scene = 'result';
  }

  // 穴に落ちた
  if (player.y > ROWS * TILE + 40) {
    loseLife();
  }

  // カメラが、自機を、なめらかに追う
  let target = player.x - width / 2;
  cameraX = lerp(cameraX, target, 0.1);
  cameraX = max(0, min(COLS * TILE - width, cameraX));
}

function loseLife() {
  lives -= 1;
  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else {
    // ステージの最初から、やり直す
    player = new Player(60, 200);
    cameraX = 0;
  }
}

// ---------- 描画 ----------

function drawWorld() {
  // 遠くの山。カメラの3割だけ、ずらす
  push();
  translate(-cameraX * 0.3, 0);
  noStroke();
  fill(120, 170, 200);
  for (let i = 0; i < 8; i++) {
    triangle(i * 220 - 60, 320, i * 220 + 80, 140, i * 220 + 220, 320);
  }
  pop();

  push();
  translate(-cameraX, 0);

  // 見えている列だけを、描く
  let first = max(0, floor(cameraX / TILE));
  let last = min(COLS - 1, first + 11);
  for (let row = 0; row < ROWS; row++) {
    for (let col = first; col <= last; col++) {
      let value = stage[row][col];
      let x = col * TILE;
      let y = row * TILE;
      if (value === 1) {
        stroke(90, 60, 40);
        strokeWeight(2);
        fill(160, 110, 70);
        rect(x, y, TILE, TILE);
        noStroke();
        fill(100, 180, 90);
        rect(x, y, TILE, 8);
      } else if (value === 2) {
        noStroke();
        fill(255, 210, 60);
        circle(x + TILE / 2, y + TILE / 2, 18);
      } else if (value === 3) {
        stroke(80);
        strokeWeight(4);
        line(x + 10, y - 80, x + 10, y + TILE);
        noStroke();
        fill(240, 80, 80);
        triangle(x + 10, y - 80, x + 50, y - 62, x + 10, y - 44);
      }
    }
  }

  for (let i = 0; i < enemies.length; i++) {
    enemies[i].show();
  }
  if (player) {
    player.show();
  }
  pop();
}

function drawStatus() {
  noStroke();
  fill(0, 0, 0, 120);
  rect(0, 0, 400, 34);
  fill(255);
  textAlign(LEFT, BASELINE);
  textSize(16);
  text(`コイン: ${coins}`, 12, 23);
  text(`残り: ${lives}`, 320, 23);
}

function drawTitle() {
  noStroke();
  fill(0, 0, 0, 140);
  rect(0, 0, 400, 400);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(30);
  text('横スクロールアクション', 200, 140);
  textSize(16);
  text('← →: 歩く   スペース: ジャンプ', 200, 200);
  text('敵は、上から踏む', 200, 230);
  text('エンターキーで、スタート', 200, 290);
}

function drawResult() {
  noStroke();
  fill(0, 0, 0, 150);
  rect(0, 0, 400, 400);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text(message, 200, 160);
  textSize(22);
  text(`コイン: ${coins}`, 200, 215);
  textSize(16);
  text('エンターキーで、タイトルへ', 200, 280);
}

function keyPressed() {
  if (key === 'Enter') {
    if (scene === 'title') {
      startGame();
      scene = 'play';
    } else if (scene === 'result') {
      scene = 'title';
    }
  }
  if (key === ' ' && scene === 'play') {
    player.jump();
  }
}

// ---------- クラス ----------

// ステージの中を動くもの。重力と、ブロックとの当たりを、受け持つ
class Actor {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.vx = 0;
    this.vy = 0;
    this.onGround = false;
    this.blocked = false;
  }

  // 四隅のどれかが、ブロックの中にあるか
  hitsBlock() {
    return isSolid(this.x, this.y) ||
      isSolid(this.x + this.w, this.y) ||
      isSolid(this.x, this.y + this.h) ||
      isSolid(this.x + this.w, this.y + this.h);
  }

  // 重力を加え、横、縦の順に動かして、ブロックに当たったら、押し戻す
  move() {
    this.vy += GRAVITY;

    this.blocked = false;
    this.x += this.vx;
    if (this.hitsBlock()) {
      if (this.vx > 0) {
        this.x = floor((this.x + this.w) / TILE) * TILE - this.w - 0.01;
      } else {
        this.x = (floor(this.x / TILE) + 1) * TILE;
      }
      this.blocked = true;
    }

    this.onGround = false;
    this.y += this.vy;
    if (this.hitsBlock()) {
      if (this.vy > 0) {
        this.y = floor((this.y + this.h) / TILE) * TILE - this.h - 0.01;
        this.onGround = true;
      } else {
        this.y = (floor(this.y / TILE) + 1) * TILE;
      }
      this.vy = 0;
    }
  }

  // 相手の四角形と、重なっているか
  overlaps(other) {
    return this.x < other.x + other.w &&
      this.x + this.w > other.x &&
      this.y < other.y + other.h &&
      this.y + this.h > other.y;
  }
}

class Player extends Actor {
  constructor(x, y) {
    super(x, y, 22, 36);
    this.direction = 1;
  }

  update() {
    this.vx = 0;
    if (keyIsDown(LEFT_ARROW)) {
      this.vx = -3.5;
      this.direction = -1;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.vx = 3.5;
      this.direction = 1;
    }
    this.move();
  }

  jump() {
    if (this.onGround) {
      this.vy = -12.5;
    }
  }

  show() {
    // 歩いているときだけ、コマを進める
    let index = 0;
    if (this.vx !== 0) {
      index = floor(frameCount / 5) % 8;
    }
    if (this.onGround === false) {
      index = 2;
    }

    push();
    translate(this.x + this.w / 2, this.y + this.h / 2 - 4);
    scale(this.direction, 1);
    imageMode(CENTER);
    image(walkImage, 0, 0, 52, 52, index * 80, 0, 80, 80);
    pop();
  }
}

// 歩いて、壁や、足場の端で、向きを変える敵
class Walker extends Actor {
  constructor(x, y) {
    super(x, y, 30, 26);
    this.dir = -1;
    this.row = 1;
  }

  update() {
    this.vx = this.dir * 1.2;
    this.move();

    // 進む先の足元に、ブロックがなければ、引き返す
    let frontX = this.x + this.w / 2 + this.dir * (this.w / 2 + 2);
    if (this.blocked || (this.onGround && isSolid(frontX, this.y + this.h + 4) === false)) {
      this.dir = -this.dir;
    }
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    imageMode(CORNER);
    image(enemyImage, this.x - 9, this.y - 16, 48, 48, frame * 64, this.row * 64, 64, 64);
  }
}

// その場で、ときどき跳ねる敵
class Hopper extends Walker {
  constructor(x, y) {
    super(x, y);
    this.row = 3;
  }

  update() {
    this.vx = 0;
    if (this.onGround && frameCount % 90 === 0) {
      this.vy = -10;
    }
    this.move();
  }
}

一度、キャンバスをクリックしてから、エンターキーを押すと、始まります。

キー 操作
←、→ 歩く
スペース ジャンプ

右へ進むと、画面が、スクロールします。穴に落ちたり、敵に、横から当たったりすると、残りが減ります。敵は、上から踏むと、倒せます。ステージの右の端にある、赤い旗が、ゴールです。


この回が終わると、次のことができるようになります。

  • ステージを、二次元配列(タイルマップ)で作り、描く
  • 重力とジャンプで動くキャラクターを、ブロックの上に、立たせる
  • 横と縦を分けて動かし、壁、床、天井との当たりを、正しく処理する
  • カメラで、広いステージを、スクロールさせる
  • 継承を使って、自機と、何種類かの敵に、共通の動きを持たせる
  • 長いプログラムを、いくつかのファイルに、分ける

全体を、設計する

データと、登場するもの

もの 表し方
ステージ 二次元配列。マスごとに、ブロック、コイン、ゴールなどの、値を持つ
自機 Player クラス
敵 Walker、Hopper クラス。配列 enemies で管理
カメラ 変数 cameraX。世界の、どこを映すか

座標が、3種類ある

このゲームでは、3種類の座標を、行き来します。

座標 単位 使う場面
マスの番号 行と列。1マスが 1 ステージの配列を、読み書きする
ワールド座標 ピクセル。ステージの左上が (0, 0) 自機や敵の位置。当たり判定
画面座標 ピクセル。キャンバスの左上が (0, 0) 実際に、描く位置

行き来の仕方は、次のとおりです。

変換 計算
マスの番号 → ワールド座標 マスの大きさを、掛ける
ワールド座標 → マスの番号 マスの大きさで割り、切り捨てる
ワールド座標 → 画面座標 カメラの位置を、引く(translate が、やってくれる)

自機と敵の位置は、いつも、ワールド座標で、持ちます。これを、頭に置いておくと、混乱しません。

作る順番

順番 作るもの
1 ステージを、マス目で作り、描く
2 重力とジャンプ。ブロックとの当たり
3 カメラで、スクロールさせる
4 敵。踏む、当たる
5 コイン、ゴール、やられ、場面、絵

ステップ1:ステージを、マス目で作る

ステージを、マス目で、組み立てます。1つのマスを、タイルと、呼びます。タイルは、40 × 40 です。キャンバスには、横に 10 枚、縦に 10 枚、並びます。

sketch.js
const TILE = 40;
const ROWS = 10;
const COLS = 30;

let stage = [];

stage[row][col] に、そのマスに、何があるかを、数で、入れます。

値 意味
0 何もない
1 ブロック

ステージを、手ぎわよく作る

横に何十マスもあるステージを、0 と 1 を、1つずつ書いて作るのは、大変です。まとめて、塗る関数を、作ります。

sketch.js
function fillTiles(row, colStart, colEnd, value) {
  for (let col = colStart; col <= colEnd; col++) {
    stage[row][col] = value;
  }
}

row 行目の、colStart 列目から、colEnd 列目までを、value に、します。

sketch.js
// 地面と、穴
fillTiles(8, 0, COLS - 1, 1);
fillTiles(9, 0, COLS - 1, 1);
fillTiles(8, 14, 16, 0);
fillTiles(9, 14, 16, 0);

// 足場
fillTiles(6, 5, 7, 1);

まず、8 行目と 9 行目を、端から端まで、ブロックで埋めます。これが、地面です。次に、その一部を、0 に戻して、穴を、空けます。それから、空中に、足場を、置きます。


「全部を埋めてから、穴を空ける」。この順番で考えると、ステージを、少ない行数で、書けます。

sketch.js
const TILE = 40;
const ROWS = 10;
const COLS = 30;

let stage = [];

function setup() {
  createCanvas(400, 400);
  makeStage();
}

function draw() {
  background(150, 200, 255);
  for (let row = 0; row < ROWS; row++) {
    for (let col = 0; col < COLS; col++) {
      if (stage[row][col] === 1) {
        stroke(90, 60, 40);
        strokeWeight(2);
        fill(160, 110, 70);
        rect(col * TILE, row * TILE, TILE, TILE);
        noStroke();
        fill(100, 180, 90);
        rect(col * TILE, row * TILE, TILE, 8);
      }
    }
  }
}

// row 行目の、colStart 列目から colEnd 列目までを、value にする
function fillTiles(row, colStart, colEnd, value) {
  for (let col = colStart; col <= colEnd; col++) {
    stage[row][col] = value;
  }
}

// ステージを作る。0:何もない 1:ブロック
function makeStage() {
  for (let row = 0; row < ROWS; row++) {
    stage[row] = [];
    for (let col = 0; col < COLS; col++) {
      stage[row][col] = 0;
    }
  }

  // 地面と、穴
  fillTiles(8, 0, COLS - 1, 1);
  fillTiles(9, 0, COLS - 1, 1);
  fillTiles(8, 14, 16, 0);
  fillTiles(9, 14, 16, 0);

  // 足場
  fillTiles(6, 5, 7, 1);
  fillTiles(4, 9, 9, 1);
  fillTiles(6, 20, 23, 1);
}

ステージの、左の端が、表示されます。地面と、空中の足場が、見えます。ステージは、横に 30 マス(1200 ピクセル)あります。キャンバスに映っているのは、そのうちの、最初の 10 マスだけです。

ステップ2:重力、ジャンプ、ブロックとの当たり

ここが、このゲームの、いちばんの山場です。キャラクターを、ブロックの上に立たせ、壁で止め、天井に頭をぶつけさせる。

四角形として、扱う

キャラクターを、四角形として、扱います。位置は、左上の角で、持ちます。

javascript
class Actor {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.vx = 0;
    this.vy = 0;
    this.onGround = false;
    this.blocked = false;
  }
}
プロパティ 意味
x、y 左上の角の位置(ワールド座標)
w、h 横幅と、高さ
vx、vy 横と縦の速度
onGround 地面に、立っているか
blocked 壁に、ぶつかったか

Actor は、「ステージの中を動くもの」を表す、親クラスです。自機も、敵も、このクラスを、継承します。重力と、ブロックとの当たりは、どちらにも、共通だからです。

ある場所が、ブロックかを調べる

ワールド座標の、ある点が、ブロックの中かどうかを、調べる関数を、作ります。

sketch.js
function tileAt(px, py) {
  let col = floor(px / TILE);
  let row = floor(py / TILE);
  if (col < 0 || col >= COLS) {
    return 1;
  }
  if (row < 0 || row >= ROWS) {
    return 0;
  }
  return stage[row][col];
}

function isSolid(px, py) {
  return tileAt(px, py) === 1;
}

座標を、タイルの大きさで割って、切り捨てると、マスの番号に、なります。その番号で、配列を読みます。


ステージの外も、決めておきます。

外れた方向 返す値 理由
左右の外 1(ブロック) ステージの端に、見えない壁を作る
上下の外 0(何もない) 上へは、跳び出せる。下へは、穴に落ちられる

配列の外を、読もうとすると、エラーになります。外のときの答えを、先に返すことで、それを、防いでいます。

四隅を調べる

四角形が、ブロックに、めり込んでいるかは、四隅の点を、調べれば、わかります。

sketch.js
hitsBlock() {
  return isSolid(this.x, this.y) ||
    isSolid(this.x + this.w, this.y) ||
    isSolid(this.x, this.y + this.h) ||
    isSolid(this.x + this.w, this.y + this.h);
}

左上、右上、左下、右下。どれか1つでも、ブロックの中にあれば、めり込んでいます。


この方法が使えるのは、キャラクターが、タイルより、小さいときです。自機は、横 22、縦 36 で、タイル(40)より、小さくしています。タイルより大きいと、四隅が、どれも、ブロックの外にあるのに、辺の真ん中が、めり込むことが、起きます。

横と縦を、分けて動かす

当たり判定の、かなめです。横の移動と、縦の移動を、別々に、行います。

javascript
move() {
  this.vy += GRAVITY;

  // 横に動かす
  this.blocked = false;
  this.x += this.vx;
  if (this.hitsBlock()) {
    // 壁に当たった。押し戻す
  }

  // 縦に動かす
  this.onGround = false;
  this.y += this.vy;
  if (this.hitsBlock()) {
    // 床か、天井に当たった。押し戻す
  }
}
順番 すること
1 重力を、縦の速度に足す
2 横だけ、動かす。めり込んだら、横に、押し戻す
3 縦だけ、動かす。めり込んだら、縦に、押し戻す

横と縦を、同時に動かすと、めり込んだとき、「壁に当たったのか、床に当たったのか」が、わかりません。斜めに落ちて、床の角に、めり込んだ。これは、横へ押し戻すべきか、縦へ押し戻すべきか。


別々に動かせば、迷いません。横に動かして、めり込んだなら、原因は、横の動きです。横へ、戻します。縦に動かして、めり込んだなら、原因は、縦の動きです。縦へ、戻します。

ぴったりの位置へ、押し戻す

めり込んだら、ブロックの、すぐ手前へ、位置を、戻します。


右へ動いて、めり込んだ場合です。

sketch.js
this.x = floor((this.x + this.w) / TILE) * TILE - this.w - 0.01;
部分 意味
this.x + this.w 四角形の、右端の座標
floor(... / TILE) * TILE 右端が入っているマスの、左端の座標。つまり、壁の面
- this.w 右端が、壁の面に来るような、x の値
- 0.01 ほんの少し、手前に。ぴったり重なると、次の判定で、めり込んだことになる

左へ動いて、めり込んだ場合は、左端が入っているマスの、右端へ、戻します。

sketch.js
this.x = (floor(this.x / TILE) + 1) * TILE;

縦も、同じ考え方です。下へ動いて、めり込んだら、床の上へ。上へ動いて、めり込んだら、天井の下へ、戻します。

立っている、を知る

sketch.js
if (this.vy > 0) {
  this.y = floor((this.y + this.h) / TILE) * TILE - this.h - 0.01;
  this.onGround = true;
} else {
  this.y = (floor(this.y / TILE) + 1) * TILE;
}
this.vy = 0;

下へ動いて、めり込んだとき、床の上に、着地しています。onGround を、true に、します。


onGround は、毎フレーム、縦に動かす前に、false に、戻しています。そして、床に当たったときだけ、true に、します。重力で、毎フレーム、少し下へ動こうとし、床に当たって、戻される。だから、床の上にいる間は、毎フレーム、true に、なります。足場から、踏み外すと、床に当たらなくなり、false のままに、なります。


床でも、天井でも、当たったら、縦の速度を、0 に、します。天井に、頭をぶつけると、上向きの速度が、0 になり、そこから、落ち始めます。

ジャンプ

sketch.js
jump() {
  if (this.onGround) {
    this.vy = -12.5;
  }
}

地面に立っているときだけ、上向きの速度を、与えます。空中では、跳べません。あとは、重力が、毎フレーム、速度を、下向きに変えていき、山なりの動きに、なります。

sketch.js
const TILE = 40;
const ROWS = 10;
const COLS = 30;
const GRAVITY = 0.6;

let stage = [];
let player;

function setup() {
  createCanvas(400, 400);
  makeStage();
  player = new Player(60, 200);
}

function draw() {
  background(150, 200, 255);

  player.update();
  if (player.y > 500) {
    player = new Player(60, 200);
  }

  for (let row = 0; row < ROWS; row++) {
    for (let col = 0; col < COLS; col++) {
      if (stage[row][col] === 1) {
        stroke(90, 60, 40);
        strokeWeight(2);
        fill(160, 110, 70);
        rect(col * TILE, row * TILE, TILE, TILE);
        noStroke();
        fill(100, 180, 90);
        rect(col * TILE, row * TILE, TILE, 8);
      }
    }
  }
  player.show();
}

function keyPressed() {
  if (key === ' ') {
    player.jump();
  }
}

// row 行目の、colStart 列目から colEnd 列目までを、value にする
function fillTiles(row, colStart, colEnd, value) {
  for (let col = colStart; col <= colEnd; col++) {
    stage[row][col] = value;
  }
}

// ステージを作る。0:何もない 1:ブロック
function makeStage() {
  for (let row = 0; row < ROWS; row++) {
    stage[row] = [];
    for (let col = 0; col < COLS; col++) {
      stage[row][col] = 0;
    }
  }

  // 地面と、穴
  fillTiles(8, 0, COLS - 1, 1);
  fillTiles(9, 0, COLS - 1, 1);
  fillTiles(8, 14, 16, 0);
  fillTiles(9, 14, 16, 0);

  // 足場
  fillTiles(6, 5, 7, 1);
  fillTiles(4, 9, 9, 1);
  fillTiles(6, 20, 23, 1);
}

// 画面上の座標 (px, py) にあるマスの、値を返す
function tileAt(px, py) {
  let col = floor(px / TILE);
  let row = floor(py / TILE);
  if (col < 0 || col >= COLS) {
    return 1;
  }
  if (row < 0 || row >= ROWS) {
    return 0;
  }
  return stage[row][col];
}

function isSolid(px, py) {
  return tileAt(px, py) === 1;
}

// ステージの中を動くもの。重力と、ブロックとの当たりを、受け持つ
class Actor {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.vx = 0;
    this.vy = 0;
    this.onGround = false;
    this.blocked = false;
  }

  // 四隅のどれかが、ブロックの中にあるか
  hitsBlock() {
    return isSolid(this.x, this.y) ||
      isSolid(this.x + this.w, this.y) ||
      isSolid(this.x, this.y + this.h) ||
      isSolid(this.x + this.w, this.y + this.h);
  }

  // 重力を加え、横、縦の順に動かして、ブロックに当たったら、押し戻す
  move() {
    this.vy += GRAVITY;

    this.blocked = false;
    this.x += this.vx;
    if (this.hitsBlock()) {
      if (this.vx > 0) {
        this.x = floor((this.x + this.w) / TILE) * TILE - this.w - 0.01;
      } else {
        this.x = (floor(this.x / TILE) + 1) * TILE;
      }
      this.blocked = true;
    }

    this.onGround = false;
    this.y += this.vy;
    if (this.hitsBlock()) {
      if (this.vy > 0) {
        this.y = floor((this.y + this.h) / TILE) * TILE - this.h - 0.01;
        this.onGround = true;
      } else {
        this.y = (floor(this.y / TILE) + 1) * TILE;
      }
      this.vy = 0;
    }
  }

  // 相手の四角形と、重なっているか
  overlaps(other) {
    return this.x < other.x + other.w &&
      this.x + this.w > other.x &&
      this.y < other.y + other.h &&
      this.y + this.h > other.y;
  }
}

class Player extends Actor {
  constructor(x, y) {
    super(x, y, 22, 36);
  }

  update() {
    this.vx = 0;
    if (keyIsDown(LEFT_ARROW)) {
      this.vx = -3.5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.vx = 3.5;
    }
    this.move();
  }

  jump() {
    if (this.onGround) {
      this.vy = -12.5;
    }
  }

  show() {
    noStroke();
    fill(240, 90, 90);
    rect(this.x, this.y, this.w, this.h, 4);
  }
}

キャンバスをクリックしてから、矢印キーと、スペースキーで、赤い四角形を、動かしてください。地面に立ち、足場に乗り、壁で止まります。足場の下から跳ぶと、頭をぶつけて、落ちます。穴に落ちると、最初の位置に、戻ります。


右へ進むと、キャンバスの外へ、出てしまいます。まだ、カメラが、ないからです。

クイズ

move() の中で、縦を先に動かし、横をあとに動かすように、順番を入れ替えたとします。動きは、変わるでしょうか?

▶ 答えを確認する

ほとんどの場面では、同じように動きます。大事なのは、「横と縦を、別々に動かして、それぞれで、押し戻す」ことです。どちらが先かは、決定的では、ありません。


違いが出るのは、ブロックの角に、斜めに、ぶつかるときです。横を先にすると、まず、横の壁として、当たります。縦を先にすると、まず、床や天井として、当たります。足場の角に、ぎりぎりで、跳び乗ろうとしたとき、乗れるか、はじかれるかが、少し、変わります。


どちらにするかは、遊んだときの感じで、決めます。この作品では、横を先に、しています。

ステップ3:カメラで、スクロールさせる

ステージは、キャンバスより、ずっと広い。カメラで、自機のまわりを、映します。

sketch.js
let target = player.x - width / 2;
cameraX = lerp(cameraX, target, 0.1);
cameraX = max(0, min(COLS * TILE - width, cameraX));
行 すること
1行目 自機が、画面の真ん中に来るような、カメラの位置を求める
2行目 いまのカメラの位置を、そこへ、10% ずつ、近づける
3行目 カメラが、ステージの外を映さないように、範囲に収める

cameraX は、カメラの左端が、ワールド座標の、どこにあるかです。0 なら、ステージの左端。最大は、「ステージの横幅 − キャンバスの横幅」です。


描くときは、translate(-cameraX, 0); で、世界の全体を、左へ、ずらします。

javascript
push();
translate(-cameraX, 0);
// ステージと、自機を、ワールド座標のまま描く
pop();

translate のあとは、ワールド座標のまま、描けば、正しい画面の位置に、表示されます。自機の位置から、カメラの位置を引く、という計算を、自分で書く必要は、ありません。

sketch.js
const TILE = 40;
const ROWS = 10;
const COLS = 30;
const GRAVITY = 0.6;

let stage = [];
let player;
let cameraX = 0;

function setup() {
  createCanvas(400, 400);
  makeStage();
  player = new Player(60, 200);
}

function draw() {
  background(150, 200, 255);

  player.update();
  if (player.y > 500) {
    player = new Player(60, 200);
  }

  // カメラが、自機を、なめらかに追う
  let target = player.x - width / 2;
  cameraX = lerp(cameraX, target, 0.1);
  cameraX = max(0, min(COLS * TILE - width, cameraX));

  push();
  translate(-cameraX, 0);
  for (let row = 0; row < ROWS; row++) {
    for (let col = 0; col < COLS; col++) {
      if (stage[row][col] === 1) {
        stroke(90, 60, 40);
        strokeWeight(2);
        fill(160, 110, 70);
        rect(col * TILE, row * TILE, TILE, TILE);
        noStroke();
        fill(100, 180, 90);
        rect(col * TILE, row * TILE, TILE, 8);
      }
    }
  }
  player.show();
  pop();
}

function keyPressed() {
  if (key === ' ') {
    player.jump();
  }
}

// row 行目の、colStart 列目から colEnd 列目までを、value にする
function fillTiles(row, colStart, colEnd, value) {
  for (let col = colStart; col <= colEnd; col++) {
    stage[row][col] = value;
  }
}

// ステージを作る。0:何もない 1:ブロック
function makeStage() {
  for (let row = 0; row < ROWS; row++) {
    stage[row] = [];
    for (let col = 0; col < COLS; col++) {
      stage[row][col] = 0;
    }
  }

  // 地面と、穴
  fillTiles(8, 0, COLS - 1, 1);
  fillTiles(9, 0, COLS - 1, 1);
  fillTiles(8, 14, 16, 0);
  fillTiles(9, 14, 16, 0);

  // 足場
  fillTiles(6, 5, 7, 1);
  fillTiles(4, 9, 9, 1);
  fillTiles(6, 20, 23, 1);
}

// 画面上の座標 (px, py) にあるマスの、値を返す
function tileAt(px, py) {
  let col = floor(px / TILE);
  let row = floor(py / TILE);
  if (col < 0 || col >= COLS) {
    return 1;
  }
  if (row < 0 || row >= ROWS) {
    return 0;
  }
  return stage[row][col];
}

function isSolid(px, py) {
  return tileAt(px, py) === 1;
}

// ステージの中を動くもの。重力と、ブロックとの当たりを、受け持つ
class Actor {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.vx = 0;
    this.vy = 0;
    this.onGround = false;
    this.blocked = false;
  }

  // 四隅のどれかが、ブロックの中にあるか
  hitsBlock() {
    return isSolid(this.x, this.y) ||
      isSolid(this.x + this.w, this.y) ||
      isSolid(this.x, this.y + this.h) ||
      isSolid(this.x + this.w, this.y + this.h);
  }

  // 重力を加え、横、縦の順に動かして、ブロックに当たったら、押し戻す
  move() {
    this.vy += GRAVITY;

    this.blocked = false;
    this.x += this.vx;
    if (this.hitsBlock()) {
      if (this.vx > 0) {
        this.x = floor((this.x + this.w) / TILE) * TILE - this.w - 0.01;
      } else {
        this.x = (floor(this.x / TILE) + 1) * TILE;
      }
      this.blocked = true;
    }

    this.onGround = false;
    this.y += this.vy;
    if (this.hitsBlock()) {
      if (this.vy > 0) {
        this.y = floor((this.y + this.h) / TILE) * TILE - this.h - 0.01;
        this.onGround = true;
      } else {
        this.y = (floor(this.y / TILE) + 1) * TILE;
      }
      this.vy = 0;
    }
  }

  // 相手の四角形と、重なっているか
  overlaps(other) {
    return this.x < other.x + other.w &&
      this.x + this.w > other.x &&
      this.y < other.y + other.h &&
      this.y + this.h > other.y;
  }
}

class Player extends Actor {
  constructor(x, y) {
    super(x, y, 22, 36);
  }

  update() {
    this.vx = 0;
    if (keyIsDown(LEFT_ARROW)) {
      this.vx = -3.5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.vx = 3.5;
    }
    this.move();
  }

  jump() {
    if (this.onGround) {
      this.vy = -12.5;
    }
  }

  show() {
    noStroke();
    fill(240, 90, 90);
    rect(this.x, this.y, this.w, this.h, 4);
  }
}

右へ進むと、景色が、左へ流れます。自機が、急に動いても、カメラは、少し遅れて、なめらかに、追いかけます。ステージの端では、カメラが止まり、自機だけが、端まで、進めます。


当たり判定は、何も、変えていません。当たり判定は、ワールド座標で、行っています。カメラは、描く位置を、ずらしているだけです。

ステップ4:敵を作る

敵も、Actor を、継承します。重力と、ブロックとの当たりは、move() を、呼ぶだけです。

歩く敵

javascript
class Walker extends Actor {
  constructor(x, y) {
    super(x, y, 30, 26);
    this.dir = -1;
    this.row = 1;
  }

  update() {
    this.vx = this.dir * 1.2;
    this.move();

    let frontX = this.x + this.w / 2 + this.dir * (this.w / 2 + 2);
    if (this.blocked || (this.onGround && isSolid(frontX, this.y + this.h + 4) === false)) {
      this.dir = -this.dir;
    }
  }
}

dir は、進む向きです。−1 なら左、1 なら右。毎フレーム、その向きに、ゆっくり、歩きます。


向きを変えるのは、次の、どちらかのときです。

条件 意味
this.blocked 壁に、ぶつかった
進む先の足元に、ブロックがない 足場の端まで来た

frontX は、進む向きの、少し先の x 座標です。その、足元より少し下(this.y + this.h + 4)が、ブロックでなければ、その先は、崖です。引き返します。


blocked は、move() の中で、横に、押し戻されたときに、true に、なります。親クラスが、「壁に当たった」ことを、記録してくれているので、子クラスは、それを、見るだけです。

跳ねる敵

sketch.js
class Hopper extends Walker {
  constructor(x, y) {
    super(x, y);
    this.row = 3;
  }

  update() {
    this.vx = 0;
    if (this.onGround && frameCount % 90 === 0) {
      this.vy = -10;
    }
    this.move();
  }
}

Hopper は、Walker を、さらに、継承しています。歩かずに、90 フレームごとに、その場で、跳ねます。絵の描き方(show)は、Walker のものを、そのまま、使います。絵の行(row)だけ、変えています。

クラス 親 自分で書いたもの
Actor なし 重力、ブロックとの当たり、四角形どうしの重なり
Player Actor キー操作、ジャンプ、絵
Walker Actor 歩く、引き返す、絵
Hopper Walker 跳ねる

いちばん難しい、ブロックとの当たりは、Actor に、1回だけ、書いてあります。自機も、2種類の敵も、それを、使い回しています。

踏んだか、当たったか

自機と敵が、重なったとき、どこから当たったかで、結果が、変わります。

sketch.js
if (player.overlaps(enemy)) {
  if (player.vy > 0 && player.y + player.h < enemy.y + enemy.h * 0.6) {
    // 上から踏んだ。敵を消して、小さく跳ねる
    enemies.splice(i, 1);
    player.vy = -8;
  } else {
    loseLife();
  }
}

overlaps は、2つの四角形が、重なっているかを、返します。Actor に、書いてあります。


踏んだと、みなすのは、次の2つが、両方とも、成り立つときです。

条件 意味
player.vy > 0 自機が、下へ、落ちている
player.y + player.h < enemy.y + enemy.h * 0.6 自機の足元が、敵の、上のほうにある

踏んだら、敵を、配列から取り除き、自機に、小さく、上向きの速度を、与えます。踏んだ反動で、ぽんと、跳ねます。そうでなければ、横や下から、当たっています。自機が、やられます。

ステップ5:ゲームとして、仕上げる

コインと、ゴール

コインと、ゴールも、タイルの値として、ステージに、置きます。

値 意味
2 コイン
3 ゴール
sketch.js
let cx = player.x + player.w / 2;
let cy = player.y + player.h / 2;
let here = tileAt(cx, cy);
if (here === 2) {
  stage[floor(cy / TILE)][floor(cx / TILE)] = 0;
  coins += 1;
}
if (here === 3) {
  message = 'ゴール!';
  scene = 'result';
}

自機の中心が、どのマスにあるかを、調べます。そこが、コイン(2)なら、そのマスを、0 に書き換えて、コインを、1 増やします。配列の値を、変えるだけで、コインは、画面から、消えます。


コインも、ゴールも、当たり判定(isSolid)では、ブロックとして、扱われません。isSolid は、値が、ちょうど 1 のときだけ、true を、返すからです。通り抜けられます。

見えている列だけを、描く

ステージは、横に 80 マス、あります。毎フレーム、800 マスを、すべて描くのは、無駄です。画面に映っている列だけを、描きます。

sketch.js
let first = max(0, floor(cameraX / TILE));
let last = min(COLS - 1, first + 11);

first は、カメラの左端がある、列の番号です。そこから、11 列先までを、描きます。キャンバスには、10 列しか入りませんが、端の列が、半分だけ見えることがあるので、1 列、多めに、描きます。

奥の山

translate(-cameraX * 0.3, 0); で、カメラの動きの、3割だけ、ずらした層に、山を、描いています。手前のステージより、ゆっくり流れ、奥行きが、出ます。

自機の絵

自機は、歩いているときだけ、コマを、進めます。

sketch.js
let index = 0;
if (this.vx !== 0) {
  index = floor(frameCount / 5) % 8;
}
if (this.onGround === false) {
  index = 2;
}
状態 コマ
止まっている 0 番(立っている絵)
歩いている 0 から 7 番を、順に
空中にいる 2 番(足を開いた絵)に、固定

direction に、向き(1 か −1)を、覚えておき、scale(this.direction, 1); で、左を向いたときに、絵を、反転しています。


絵は、当たり判定の四角形(22 × 36)より、大きく(52 × 52)、描いています。当たり判定を、見た目より、少し小さくしておくと、ぎりぎりで、すり抜けられて、遊びやすくなります。

やられたとき

sketch.js
function loseLife() {
  lives -= 1;
  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else {
    // ステージの最初から、やり直す
    player = new Player(60, 200);
    cameraX = 0;
  }
}

敵に当たったときも、穴に落ちたときも、同じ関数を、呼びます。残りがあれば、自機を、新しく作り直して、最初の位置に、戻します。位置、速度、向き。すべてが、まとめて、最初の状態に、戻ります。

完成したプログラムの、全体

冒頭のプログラムが、完成形です。プログラムは、4つの、まとまりに、分かれています。

まとまり 内容
ステージ fillTiles、makeStage、tileAt、isSolid
ゲームの進行 startGame、updateGame、loseLife、keyPressed
描画 drawWorld、drawStatus、drawTitle、drawResult
クラス Actor、Player、Walker、Hopper

ファイルに、分ける

プログラムは、350 行ほどに、なりました。1つのファイルに、すべてが入っていると、目的の場所を、探すのが、大変です。まとまりごとに、ファイルを分けます。

ファイル 中身
sketch.js 定数、変数、setup、draw、ゲームの進行、描画
stage.js ステージを作る関数、マスを調べる関数
actor.js Actor クラス
player.js Player クラス
enemy.js Walker、Hopper クラス

p5.js のエディタで、ファイルを足し、index.html に、読み込む行を、書き足します。

index.html
<script src="actor.js"></script>
<script src="player.js"></script>
<script src="enemy.js"></script>
<script src="stage.js"></script>
<script src="sketch.js"></script>

順番に、気を付けます。Player は、Actor を、継承しています。Actor が、先に、読み込まれていないと、Player を、作れません。親クラスのファイルを、子クラスのファイルより、先に、書きます。Hopper は Walker を継承しているので、同じファイルの中で、Walker を、先に書きます。


ファイルを分けても、プログラムの中身は、1文字も、変わりません。変わるのは、置き場所だけです。敵を足したくなったら、enemy.js を、開く。ステージを直したくなったら、stage.js を、開く。どこを見ればよいかが、ファイルの名前で、わかるようになります。

やってみよう

次の3つを作ってください。

  1. 空中で、もう1回だけ跳べる、2段ジャンプを、作る
  2. 3種類目の敵として、速く走り、足場の端でも止まらない敵を、足す。壁に当たったときだけ、引き返す
  3. ゴールの手前に、階段と、その上のコインを、足す
▶ 1. 2段ジャンプ

jumps というプロパティで、何回、跳んだかを、数えます。地面から跳んだら 1。空中で、jumps が 1 のときだけ、もう一度、跳べて、2 にします。

sketch.js
const TILE = 40;
const ROWS = 10;
const COLS = 80;
const GRAVITY = 0.6;

let walkImage;
let enemyImage;

let scene = 'title';
let message = '';
let stage = [];
let player;
let enemies = [];
let cameraX = 0;
let coins = 0;
let lives = 3;

async function setup() {
  createCanvas(400, 400);
  walkImage = await loadImage('walk.png');
  enemyImage = await loadImage('enemies.png');
  makeStage();
}

function draw() {
  background(150, 200, 255);

  if (scene === 'title') {
    drawWorld();
    drawTitle();
  } else if (scene === 'play') {
    updateGame();
    drawWorld();
    drawStatus();
  } else if (scene === 'result') {
    drawWorld();
    drawStatus();
    drawResult();
  }
}

// ---------- ステージ ----------

// row 行目の、colStart 列目から colEnd 列目までを、value にする
function fillTiles(row, colStart, colEnd, value) {
  for (let col = colStart; col <= colEnd; col++) {
    stage[row][col] = value;
  }
}

// ステージを作る。0:何もない 1:ブロック 2:コイン 3:ゴール
function makeStage() {
  for (let row = 0; row < ROWS; row++) {
    stage[row] = [];
    for (let col = 0; col < COLS; col++) {
      stage[row][col] = 0;
    }
  }

  // 地面と、穴
  fillTiles(8, 0, COLS - 1, 1);
  fillTiles(9, 0, COLS - 1, 1);
  fillTiles(8, 14, 16, 0);
  fillTiles(9, 14, 16, 0);
  fillTiles(8, 33, 36, 0);
  fillTiles(9, 33, 36, 0);
  fillTiles(8, 55, 57, 0);
  fillTiles(9, 55, 57, 0);

  // 足場
  fillTiles(6, 7, 9, 1);
  fillTiles(5, 20, 23, 1);
  fillTiles(3, 25, 27, 1);
  fillTiles(6, 34, 35, 1);
  fillTiles(7, 42, 42, 1);
  fillTiles(6, 43, 43, 1);
  fillTiles(5, 44, 48, 1);
  fillTiles(5, 61, 63, 1);
  fillTiles(3, 66, 68, 1);

  // コイン
  fillTiles(5, 7, 9, 2);
  fillTiles(4, 20, 23, 2);
  fillTiles(2, 25, 27, 2);
  fillTiles(4, 45, 47, 2);
  fillTiles(2, 66, 68, 2);
  fillTiles(6, 15, 15, 2);

  // ゴール
  stage[7][76] = 3;

  enemies = [];
  enemies.push(new Walker(11 * TILE, 7 * TILE));
  enemies.push(new Walker(21 * TILE, 4 * TILE));
  enemies.push(new Walker(29 * TILE, 7 * TILE));
  enemies.push(new Hopper(40 * TILE, 7 * TILE));
  enemies.push(new Walker(46 * TILE, 4 * TILE));
  enemies.push(new Hopper(52 * TILE, 7 * TILE));
  enemies.push(new Walker(62 * TILE, 4 * TILE));
  enemies.push(new Walker(70 * TILE, 7 * TILE));
}

// 画面上の座標 (px, py) にあるマスの、値を返す
function tileAt(px, py) {
  let col = floor(px / TILE);
  let row = floor(py / TILE);
  if (col < 0 || col >= COLS) {
    return 1;
  }
  if (row < 0 || row >= ROWS) {
    return 0;
  }
  return stage[row][col];
}

function isSolid(px, py) {
  return tileAt(px, py) === 1;
}

// ---------- ゲームの進行 ----------

function startGame() {
  makeStage();
  player = new Player(60, 200);
  cameraX = 0;
  coins = 0;
  lives = 3;
}

function updateGame() {
  player.update();

  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();

    if (player.overlaps(enemy)) {
      if (player.vy > 0 && player.y + player.h < enemy.y + enemy.h * 0.6) {
        // 上から踏んだ。敵を消して、小さく跳ねる
        enemies.splice(i, 1);
        player.vy = -8;
      } else {
        loseLife();
      }
    }
  }

  // コインと、ゴール。自機の中心がある、マスを調べる
  let cx = player.x + player.w / 2;
  let cy = player.y + player.h / 2;
  let here = tileAt(cx, cy);
  if (here === 2) {
    stage[floor(cy / TILE)][floor(cx / TILE)] = 0;
    coins += 1;
  }
  if (here === 3) {
    message = 'ゴール!';
    scene = 'result';
  }

  // 穴に落ちた
  if (player.y > ROWS * TILE + 40) {
    loseLife();
  }

  // カメラが、自機を、なめらかに追う
  let target = player.x - width / 2;
  cameraX = lerp(cameraX, target, 0.1);
  cameraX = max(0, min(COLS * TILE - width, cameraX));
}

function loseLife() {
  lives -= 1;
  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else {
    // ステージの最初から、やり直す
    player = new Player(60, 200);
    cameraX = 0;
  }
}

// ---------- 描画 ----------

function drawWorld() {
  // 遠くの山。カメラの3割だけ、ずらす
  push();
  translate(-cameraX * 0.3, 0);
  noStroke();
  fill(120, 170, 200);
  for (let i = 0; i < 8; i++) {
    triangle(i * 220 - 60, 320, i * 220 + 80, 140, i * 220 + 220, 320);
  }
  pop();

  push();
  translate(-cameraX, 0);

  // 見えている列だけを、描く
  let first = max(0, floor(cameraX / TILE));
  let last = min(COLS - 1, first + 11);
  for (let row = 0; row < ROWS; row++) {
    for (let col = first; col <= last; col++) {
      let value = stage[row][col];
      let x = col * TILE;
      let y = row * TILE;
      if (value === 1) {
        stroke(90, 60, 40);
        strokeWeight(2);
        fill(160, 110, 70);
        rect(x, y, TILE, TILE);
        noStroke();
        fill(100, 180, 90);
        rect(x, y, TILE, 8);
      } else if (value === 2) {
        noStroke();
        fill(255, 210, 60);
        circle(x + TILE / 2, y + TILE / 2, 18);
      } else if (value === 3) {
        stroke(80);
        strokeWeight(4);
        line(x + 10, y - 80, x + 10, y + TILE);
        noStroke();
        fill(240, 80, 80);
        triangle(x + 10, y - 80, x + 50, y - 62, x + 10, y - 44);
      }
    }
  }

  for (let i = 0; i < enemies.length; i++) {
    enemies[i].show();
  }
  if (player) {
    player.show();
  }
  pop();
}

function drawStatus() {
  noStroke();
  fill(0, 0, 0, 120);
  rect(0, 0, 400, 34);
  fill(255);
  textAlign(LEFT, BASELINE);
  textSize(16);
  text(`コイン: ${coins}`, 12, 23);
  text(`残り: ${lives}`, 320, 23);
}

function drawTitle() {
  noStroke();
  fill(0, 0, 0, 140);
  rect(0, 0, 400, 400);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(30);
  text('横スクロールアクション', 200, 140);
  textSize(16);
  text('← →: 歩く   スペース: ジャンプ', 200, 200);
  text('敵は、上から踏む', 200, 230);
  text('エンターキーで、スタート', 200, 290);
}

function drawResult() {
  noStroke();
  fill(0, 0, 0, 150);
  rect(0, 0, 400, 400);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text(message, 200, 160);
  textSize(22);
  text(`コイン: ${coins}`, 200, 215);
  textSize(16);
  text('エンターキーで、タイトルへ', 200, 280);
}

function keyPressed() {
  if (key === 'Enter') {
    if (scene === 'title') {
      startGame();
      scene = 'play';
    } else if (scene === 'result') {
      scene = 'title';
    }
  }
  if (key === ' ' && scene === 'play') {
    player.jump();
  }
}

// ---------- クラス ----------

// ステージの中を動くもの。重力と、ブロックとの当たりを、受け持つ
class Actor {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.vx = 0;
    this.vy = 0;
    this.onGround = false;
    this.blocked = false;
  }

  // 四隅のどれかが、ブロックの中にあるか
  hitsBlock() {
    return isSolid(this.x, this.y) ||
      isSolid(this.x + this.w, this.y) ||
      isSolid(this.x, this.y + this.h) ||
      isSolid(this.x + this.w, this.y + this.h);
  }

  // 重力を加え、横、縦の順に動かして、ブロックに当たったら、押し戻す
  move() {
    this.vy += GRAVITY;

    this.blocked = false;
    this.x += this.vx;
    if (this.hitsBlock()) {
      if (this.vx > 0) {
        this.x = floor((this.x + this.w) / TILE) * TILE - this.w - 0.01;
      } else {
        this.x = (floor(this.x / TILE) + 1) * TILE;
      }
      this.blocked = true;
    }

    this.onGround = false;
    this.y += this.vy;
    if (this.hitsBlock()) {
      if (this.vy > 0) {
        this.y = floor((this.y + this.h) / TILE) * TILE - this.h - 0.01;
        this.onGround = true;
      } else {
        this.y = (floor(this.y / TILE) + 1) * TILE;
      }
      this.vy = 0;
    }
  }

  // 相手の四角形と、重なっているか
  overlaps(other) {
    return this.x < other.x + other.w &&
      this.x + this.w > other.x &&
      this.y < other.y + other.h &&
      this.y + this.h > other.y;
  }
}

class Player extends Actor {
  constructor(x, y) {
    super(x, y, 22, 36);
    this.direction = 1;
    this.jumps = 0;
  }

  update() {
    this.vx = 0;
    if (keyIsDown(LEFT_ARROW)) {
      this.vx = -3.5;
      this.direction = -1;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.vx = 3.5;
      this.direction = 1;
    }
    this.move();
  }

  jump() {
    if (this.onGround) {
      this.vy = -12.5;
      this.jumps = 1;
    } else if (this.jumps === 1) {
      // 空中で、もう1回だけ、跳べる
      this.vy = -10;
      this.jumps = 2;
    }
  }

  show() {
    // 歩いているときだけ、コマを進める
    let index = 0;
    if (this.vx !== 0) {
      index = floor(frameCount / 5) % 8;
    }
    if (this.onGround === false) {
      index = 2;
    }

    push();
    translate(this.x + this.w / 2, this.y + this.h / 2 - 4);
    scale(this.direction, 1);
    imageMode(CENTER);
    image(walkImage, 0, 0, 52, 52, index * 80, 0, 80, 80);
    pop();
  }
}

// 歩いて、壁や、足場の端で、向きを変える敵
class Walker extends Actor {
  constructor(x, y) {
    super(x, y, 30, 26);
    this.dir = -1;
    this.row = 1;
  }

  update() {
    this.vx = this.dir * 1.2;
    this.move();

    // 進む先の足元に、ブロックがなければ、引き返す
    let frontX = this.x + this.w / 2 + this.dir * (this.w / 2 + 2);
    if (this.blocked || (this.onGround && isSolid(frontX, this.y + this.h + 4) === false)) {
      this.dir = -this.dir;
    }
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    imageMode(CORNER);
    image(enemyImage, this.x - 9, this.y - 16, 48, 48, frame * 64, this.row * 64, 64, 64);
  }
}

// その場で、ときどき跳ねる敵
class Hopper extends Walker {
  constructor(x, y) {
    super(x, y);
    this.row = 3;
  }

  update() {
    this.vx = 0;
    if (this.onGround && frameCount % 90 === 0) {
      this.vy = -10;
    }
    this.move();
  }
}

地面から跳ぶと、jumps が 1 に、戻ります。だから、着地するたびに、また、2回、跳べます。2回目のジャンプは、少し、弱くしています。


届かなかった足場に、届くようになり、穴を、落ちかけてから、立て直すことも、できます。直したのは、Player クラスの中だけです。

▶ 2. 速く走る敵

Walker を継承して、update() を、書き直します。足元を調べる処理を、なくし、壁に当たったとき(blocked)だけ、向きを変えます。

sketch.js
const TILE = 40;
const ROWS = 10;
const COLS = 80;
const GRAVITY = 0.6;

let walkImage;
let enemyImage;

let scene = 'title';
let message = '';
let stage = [];
let player;
let enemies = [];
let cameraX = 0;
let coins = 0;
let lives = 3;

async function setup() {
  createCanvas(400, 400);
  walkImage = await loadImage('walk.png');
  enemyImage = await loadImage('enemies.png');
  makeStage();
}

function draw() {
  background(150, 200, 255);

  if (scene === 'title') {
    drawWorld();
    drawTitle();
  } else if (scene === 'play') {
    updateGame();
    drawWorld();
    drawStatus();
  } else if (scene === 'result') {
    drawWorld();
    drawStatus();
    drawResult();
  }
}

// ---------- ステージ ----------

// row 行目の、colStart 列目から colEnd 列目までを、value にする
function fillTiles(row, colStart, colEnd, value) {
  for (let col = colStart; col <= colEnd; col++) {
    stage[row][col] = value;
  }
}

// ステージを作る。0:何もない 1:ブロック 2:コイン 3:ゴール
function makeStage() {
  for (let row = 0; row < ROWS; row++) {
    stage[row] = [];
    for (let col = 0; col < COLS; col++) {
      stage[row][col] = 0;
    }
  }

  // 地面と、穴
  fillTiles(8, 0, COLS - 1, 1);
  fillTiles(9, 0, COLS - 1, 1);
  fillTiles(8, 14, 16, 0);
  fillTiles(9, 14, 16, 0);
  fillTiles(8, 33, 36, 0);
  fillTiles(9, 33, 36, 0);
  fillTiles(8, 55, 57, 0);
  fillTiles(9, 55, 57, 0);

  // 足場
  fillTiles(6, 7, 9, 1);
  fillTiles(5, 20, 23, 1);
  fillTiles(3, 25, 27, 1);
  fillTiles(6, 34, 35, 1);
  fillTiles(7, 42, 42, 1);
  fillTiles(6, 43, 43, 1);
  fillTiles(5, 44, 48, 1);
  fillTiles(5, 61, 63, 1);
  fillTiles(3, 66, 68, 1);

  // コイン
  fillTiles(5, 7, 9, 2);
  fillTiles(4, 20, 23, 2);
  fillTiles(2, 25, 27, 2);
  fillTiles(4, 45, 47, 2);
  fillTiles(2, 66, 68, 2);
  fillTiles(6, 15, 15, 2);

  // ゴール
  stage[7][76] = 3;

  enemies = [];
  enemies.push(new Walker(11 * TILE, 7 * TILE));
  enemies.push(new Walker(21 * TILE, 4 * TILE));
  enemies.push(new Runner(29 * TILE, 7 * TILE));
  enemies.push(new Hopper(40 * TILE, 7 * TILE));
  enemies.push(new Walker(46 * TILE, 4 * TILE));
  enemies.push(new Hopper(52 * TILE, 7 * TILE));
  enemies.push(new Walker(62 * TILE, 4 * TILE));
  enemies.push(new Walker(70 * TILE, 7 * TILE));
}

// 画面上の座標 (px, py) にあるマスの、値を返す
function tileAt(px, py) {
  let col = floor(px / TILE);
  let row = floor(py / TILE);
  if (col < 0 || col >= COLS) {
    return 1;
  }
  if (row < 0 || row >= ROWS) {
    return 0;
  }
  return stage[row][col];
}

function isSolid(px, py) {
  return tileAt(px, py) === 1;
}

// ---------- ゲームの進行 ----------

function startGame() {
  makeStage();
  player = new Player(60, 200);
  cameraX = 0;
  coins = 0;
  lives = 3;
}

function updateGame() {
  player.update();

  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();

    if (player.overlaps(enemy)) {
      if (player.vy > 0 && player.y + player.h < enemy.y + enemy.h * 0.6) {
        // 上から踏んだ。敵を消して、小さく跳ねる
        enemies.splice(i, 1);
        player.vy = -8;
      } else {
        loseLife();
      }
    }
  }

  // コインと、ゴール。自機の中心がある、マスを調べる
  let cx = player.x + player.w / 2;
  let cy = player.y + player.h / 2;
  let here = tileAt(cx, cy);
  if (here === 2) {
    stage[floor(cy / TILE)][floor(cx / TILE)] = 0;
    coins += 1;
  }
  if (here === 3) {
    message = 'ゴール!';
    scene = 'result';
  }

  // 穴に落ちた
  if (player.y > ROWS * TILE + 40) {
    loseLife();
  }

  // カメラが、自機を、なめらかに追う
  let target = player.x - width / 2;
  cameraX = lerp(cameraX, target, 0.1);
  cameraX = max(0, min(COLS * TILE - width, cameraX));
}

function loseLife() {
  lives -= 1;
  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else {
    // ステージの最初から、やり直す
    player = new Player(60, 200);
    cameraX = 0;
  }
}

// ---------- 描画 ----------

function drawWorld() {
  // 遠くの山。カメラの3割だけ、ずらす
  push();
  translate(-cameraX * 0.3, 0);
  noStroke();
  fill(120, 170, 200);
  for (let i = 0; i < 8; i++) {
    triangle(i * 220 - 60, 320, i * 220 + 80, 140, i * 220 + 220, 320);
  }
  pop();

  push();
  translate(-cameraX, 0);

  // 見えている列だけを、描く
  let first = max(0, floor(cameraX / TILE));
  let last = min(COLS - 1, first + 11);
  for (let row = 0; row < ROWS; row++) {
    for (let col = first; col <= last; col++) {
      let value = stage[row][col];
      let x = col * TILE;
      let y = row * TILE;
      if (value === 1) {
        stroke(90, 60, 40);
        strokeWeight(2);
        fill(160, 110, 70);
        rect(x, y, TILE, TILE);
        noStroke();
        fill(100, 180, 90);
        rect(x, y, TILE, 8);
      } else if (value === 2) {
        noStroke();
        fill(255, 210, 60);
        circle(x + TILE / 2, y + TILE / 2, 18);
      } else if (value === 3) {
        stroke(80);
        strokeWeight(4);
        line(x + 10, y - 80, x + 10, y + TILE);
        noStroke();
        fill(240, 80, 80);
        triangle(x + 10, y - 80, x + 50, y - 62, x + 10, y - 44);
      }
    }
  }

  for (let i = 0; i < enemies.length; i++) {
    enemies[i].show();
  }
  if (player) {
    player.show();
  }
  pop();
}

function drawStatus() {
  noStroke();
  fill(0, 0, 0, 120);
  rect(0, 0, 400, 34);
  fill(255);
  textAlign(LEFT, BASELINE);
  textSize(16);
  text(`コイン: ${coins}`, 12, 23);
  text(`残り: ${lives}`, 320, 23);
}

function drawTitle() {
  noStroke();
  fill(0, 0, 0, 140);
  rect(0, 0, 400, 400);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(30);
  text('横スクロールアクション', 200, 140);
  textSize(16);
  text('← →: 歩く   スペース: ジャンプ', 200, 200);
  text('敵は、上から踏む', 200, 230);
  text('エンターキーで、スタート', 200, 290);
}

function drawResult() {
  noStroke();
  fill(0, 0, 0, 150);
  rect(0, 0, 400, 400);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text(message, 200, 160);
  textSize(22);
  text(`コイン: ${coins}`, 200, 215);
  textSize(16);
  text('エンターキーで、タイトルへ', 200, 280);
}

function keyPressed() {
  if (key === 'Enter') {
    if (scene === 'title') {
      startGame();
      scene = 'play';
    } else if (scene === 'result') {
      scene = 'title';
    }
  }
  if (key === ' ' && scene === 'play') {
    player.jump();
  }
}

// ---------- クラス ----------

// ステージの中を動くもの。重力と、ブロックとの当たりを、受け持つ
class Actor {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.vx = 0;
    this.vy = 0;
    this.onGround = false;
    this.blocked = false;
  }

  // 四隅のどれかが、ブロックの中にあるか
  hitsBlock() {
    return isSolid(this.x, this.y) ||
      isSolid(this.x + this.w, this.y) ||
      isSolid(this.x, this.y + this.h) ||
      isSolid(this.x + this.w, this.y + this.h);
  }

  // 重力を加え、横、縦の順に動かして、ブロックに当たったら、押し戻す
  move() {
    this.vy += GRAVITY;

    this.blocked = false;
    this.x += this.vx;
    if (this.hitsBlock()) {
      if (this.vx > 0) {
        this.x = floor((this.x + this.w) / TILE) * TILE - this.w - 0.01;
      } else {
        this.x = (floor(this.x / TILE) + 1) * TILE;
      }
      this.blocked = true;
    }

    this.onGround = false;
    this.y += this.vy;
    if (this.hitsBlock()) {
      if (this.vy > 0) {
        this.y = floor((this.y + this.h) / TILE) * TILE - this.h - 0.01;
        this.onGround = true;
      } else {
        this.y = (floor(this.y / TILE) + 1) * TILE;
      }
      this.vy = 0;
    }
  }

  // 相手の四角形と、重なっているか
  overlaps(other) {
    return this.x < other.x + other.w &&
      this.x + this.w > other.x &&
      this.y < other.y + other.h &&
      this.y + this.h > other.y;
  }
}

class Player extends Actor {
  constructor(x, y) {
    super(x, y, 22, 36);
    this.direction = 1;
  }

  update() {
    this.vx = 0;
    if (keyIsDown(LEFT_ARROW)) {
      this.vx = -3.5;
      this.direction = -1;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.vx = 3.5;
      this.direction = 1;
    }
    this.move();
  }

  jump() {
    if (this.onGround) {
      this.vy = -12.5;
    }
  }

  show() {
    // 歩いているときだけ、コマを進める
    let index = 0;
    if (this.vx !== 0) {
      index = floor(frameCount / 5) % 8;
    }
    if (this.onGround === false) {
      index = 2;
    }

    push();
    translate(this.x + this.w / 2, this.y + this.h / 2 - 4);
    scale(this.direction, 1);
    imageMode(CENTER);
    image(walkImage, 0, 0, 52, 52, index * 80, 0, 80, 80);
    pop();
  }
}

// 歩いて、壁や、足場の端で、向きを変える敵
class Walker extends Actor {
  constructor(x, y) {
    super(x, y, 30, 26);
    this.dir = -1;
    this.row = 1;
  }

  update() {
    this.vx = this.dir * 1.2;
    this.move();

    // 進む先の足元に、ブロックがなければ、引き返す
    let frontX = this.x + this.w / 2 + this.dir * (this.w / 2 + 2);
    if (this.blocked || (this.onGround && isSolid(frontX, this.y + this.h + 4) === false)) {
      this.dir = -this.dir;
    }
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    imageMode(CORNER);
    image(enemyImage, this.x - 9, this.y - 16, 48, 48, frame * 64, this.row * 64, 64, 64);
  }
}

// 壁に当たるまで、速く走る敵。足場の端でも、止まらない
class Runner extends Walker {
  constructor(x, y) {
    super(x, y);
    this.row = 2;
  }

  update() {
    this.vx = this.dir * 3;
    this.move();
    if (this.blocked) {
      this.dir = -this.dir;
    }
  }
}

// その場で、ときどき跳ねる敵
class Hopper extends Walker {
  constructor(x, y) {
    super(x, y);
    this.row = 3;
  }

  update() {
    this.vx = 0;
    if (this.onGround && frameCount % 90 === 0) {
      this.vy = -10;
    }
    this.move();
  }
}

この敵は、足場の端で、止まりません。そのまま、飛び出して、落ちていきます。地面の上では、穴に落ちるまで、走り続けます。重力も、落下も、move() が、やってくれるので、何も、書き足していません。

▶ 3. ゴールの手前に、階段を足す

makeStage の中に、fillTiles を、数行、足します。

sketch.js
const TILE = 40;
const ROWS = 10;
const COLS = 80;
const GRAVITY = 0.6;

let walkImage;
let enemyImage;

let scene = 'title';
let message = '';
let stage = [];
let player;
let enemies = [];
let cameraX = 0;
let coins = 0;
let lives = 3;

async function setup() {
  createCanvas(400, 400);
  walkImage = await loadImage('walk.png');
  enemyImage = await loadImage('enemies.png');
  makeStage();
}

function draw() {
  background(150, 200, 255);

  if (scene === 'title') {
    drawWorld();
    drawTitle();
  } else if (scene === 'play') {
    updateGame();
    drawWorld();
    drawStatus();
  } else if (scene === 'result') {
    drawWorld();
    drawStatus();
    drawResult();
  }
}

// ---------- ステージ ----------

// row 行目の、colStart 列目から colEnd 列目までを、value にする
function fillTiles(row, colStart, colEnd, value) {
  for (let col = colStart; col <= colEnd; col++) {
    stage[row][col] = value;
  }
}

// ステージを作る。0:何もない 1:ブロック 2:コイン 3:ゴール
function makeStage() {
  for (let row = 0; row < ROWS; row++) {
    stage[row] = [];
    for (let col = 0; col < COLS; col++) {
      stage[row][col] = 0;
    }
  }

  // 地面と、穴
  fillTiles(8, 0, COLS - 1, 1);
  fillTiles(9, 0, COLS - 1, 1);
  fillTiles(8, 14, 16, 0);
  fillTiles(9, 14, 16, 0);
  fillTiles(8, 33, 36, 0);
  fillTiles(9, 33, 36, 0);
  fillTiles(8, 55, 57, 0);
  fillTiles(9, 55, 57, 0);

  // 足場
  fillTiles(6, 7, 9, 1);
  fillTiles(5, 20, 23, 1);
  fillTiles(3, 25, 27, 1);
  fillTiles(6, 34, 35, 1);
  fillTiles(7, 42, 42, 1);
  fillTiles(6, 43, 43, 1);
  fillTiles(5, 44, 48, 1);
  fillTiles(5, 61, 63, 1);
  fillTiles(3, 66, 68, 1);

  // コイン
  fillTiles(5, 7, 9, 2);
  fillTiles(4, 20, 23, 2);
  fillTiles(2, 25, 27, 2);
  fillTiles(4, 45, 47, 2);
  fillTiles(2, 66, 68, 2);
  fillTiles(6, 15, 15, 2);

  // ゴールの手前に、階段を足す
  fillTiles(7, 71, 74, 1);
  fillTiles(6, 72, 74, 1);
  fillTiles(5, 73, 74, 1);
  fillTiles(4, 73, 74, 2);

  // ゴール
  stage[7][76] = 3;

  enemies = [];
  enemies.push(new Walker(11 * TILE, 7 * TILE));
  enemies.push(new Walker(21 * TILE, 4 * TILE));
  enemies.push(new Walker(29 * TILE, 7 * TILE));
  enemies.push(new Hopper(40 * TILE, 7 * TILE));
  enemies.push(new Walker(46 * TILE, 4 * TILE));
  enemies.push(new Hopper(52 * TILE, 7 * TILE));
  enemies.push(new Walker(62 * TILE, 4 * TILE));
  enemies.push(new Walker(68 * TILE, 7 * TILE));
}

// 画面上の座標 (px, py) にあるマスの、値を返す
function tileAt(px, py) {
  let col = floor(px / TILE);
  let row = floor(py / TILE);
  if (col < 0 || col >= COLS) {
    return 1;
  }
  if (row < 0 || row >= ROWS) {
    return 0;
  }
  return stage[row][col];
}

function isSolid(px, py) {
  return tileAt(px, py) === 1;
}

// ---------- ゲームの進行 ----------

function startGame() {
  makeStage();
  player = new Player(60, 200);
  cameraX = 0;
  coins = 0;
  lives = 3;
}

function updateGame() {
  player.update();

  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();

    if (player.overlaps(enemy)) {
      if (player.vy > 0 && player.y + player.h < enemy.y + enemy.h * 0.6) {
        // 上から踏んだ。敵を消して、小さく跳ねる
        enemies.splice(i, 1);
        player.vy = -8;
      } else {
        loseLife();
      }
    }
  }

  // コインと、ゴール。自機の中心がある、マスを調べる
  let cx = player.x + player.w / 2;
  let cy = player.y + player.h / 2;
  let here = tileAt(cx, cy);
  if (here === 2) {
    stage[floor(cy / TILE)][floor(cx / TILE)] = 0;
    coins += 1;
  }
  if (here === 3) {
    message = 'ゴール!';
    scene = 'result';
  }

  // 穴に落ちた
  if (player.y > ROWS * TILE + 40) {
    loseLife();
  }

  // カメラが、自機を、なめらかに追う
  let target = player.x - width / 2;
  cameraX = lerp(cameraX, target, 0.1);
  cameraX = max(0, min(COLS * TILE - width, cameraX));
}

function loseLife() {
  lives -= 1;
  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else {
    // ステージの最初から、やり直す
    player = new Player(60, 200);
    cameraX = 0;
  }
}

// ---------- 描画 ----------

function drawWorld() {
  // 遠くの山。カメラの3割だけ、ずらす
  push();
  translate(-cameraX * 0.3, 0);
  noStroke();
  fill(120, 170, 200);
  for (let i = 0; i < 8; i++) {
    triangle(i * 220 - 60, 320, i * 220 + 80, 140, i * 220 + 220, 320);
  }
  pop();

  push();
  translate(-cameraX, 0);

  // 見えている列だけを、描く
  let first = max(0, floor(cameraX / TILE));
  let last = min(COLS - 1, first + 11);
  for (let row = 0; row < ROWS; row++) {
    for (let col = first; col <= last; col++) {
      let value = stage[row][col];
      let x = col * TILE;
      let y = row * TILE;
      if (value === 1) {
        stroke(90, 60, 40);
        strokeWeight(2);
        fill(160, 110, 70);
        rect(x, y, TILE, TILE);
        noStroke();
        fill(100, 180, 90);
        rect(x, y, TILE, 8);
      } else if (value === 2) {
        noStroke();
        fill(255, 210, 60);
        circle(x + TILE / 2, y + TILE / 2, 18);
      } else if (value === 3) {
        stroke(80);
        strokeWeight(4);
        line(x + 10, y - 80, x + 10, y + TILE);
        noStroke();
        fill(240, 80, 80);
        triangle(x + 10, y - 80, x + 50, y - 62, x + 10, y - 44);
      }
    }
  }

  for (let i = 0; i < enemies.length; i++) {
    enemies[i].show();
  }
  if (player) {
    player.show();
  }
  pop();
}

function drawStatus() {
  noStroke();
  fill(0, 0, 0, 120);
  rect(0, 0, 400, 34);
  fill(255);
  textAlign(LEFT, BASELINE);
  textSize(16);
  text(`コイン: ${coins}`, 12, 23);
  text(`残り: ${lives}`, 320, 23);
}

function drawTitle() {
  noStroke();
  fill(0, 0, 0, 140);
  rect(0, 0, 400, 400);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(30);
  text('横スクロールアクション', 200, 140);
  textSize(16);
  text('← →: 歩く   スペース: ジャンプ', 200, 200);
  text('敵は、上から踏む', 200, 230);
  text('エンターキーで、スタート', 200, 290);
}

function drawResult() {
  noStroke();
  fill(0, 0, 0, 150);
  rect(0, 0, 400, 400);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text(message, 200, 160);
  textSize(22);
  text(`コイン: ${coins}`, 200, 215);
  textSize(16);
  text('エンターキーで、タイトルへ', 200, 280);
}

function keyPressed() {
  if (key === 'Enter') {
    if (scene === 'title') {
      startGame();
      scene = 'play';
    } else if (scene === 'result') {
      scene = 'title';
    }
  }
  if (key === ' ' && scene === 'play') {
    player.jump();
  }
}

// ---------- クラス ----------

// ステージの中を動くもの。重力と、ブロックとの当たりを、受け持つ
class Actor {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.vx = 0;
    this.vy = 0;
    this.onGround = false;
    this.blocked = false;
  }

  // 四隅のどれかが、ブロックの中にあるか
  hitsBlock() {
    return isSolid(this.x, this.y) ||
      isSolid(this.x + this.w, this.y) ||
      isSolid(this.x, this.y + this.h) ||
      isSolid(this.x + this.w, this.y + this.h);
  }

  // 重力を加え、横、縦の順に動かして、ブロックに当たったら、押し戻す
  move() {
    this.vy += GRAVITY;

    this.blocked = false;
    this.x += this.vx;
    if (this.hitsBlock()) {
      if (this.vx > 0) {
        this.x = floor((this.x + this.w) / TILE) * TILE - this.w - 0.01;
      } else {
        this.x = (floor(this.x / TILE) + 1) * TILE;
      }
      this.blocked = true;
    }

    this.onGround = false;
    this.y += this.vy;
    if (this.hitsBlock()) {
      if (this.vy > 0) {
        this.y = floor((this.y + this.h) / TILE) * TILE - this.h - 0.01;
        this.onGround = true;
      } else {
        this.y = (floor(this.y / TILE) + 1) * TILE;
      }
      this.vy = 0;
    }
  }

  // 相手の四角形と、重なっているか
  overlaps(other) {
    return this.x < other.x + other.w &&
      this.x + this.w > other.x &&
      this.y < other.y + other.h &&
      this.y + this.h > other.y;
  }
}

class Player extends Actor {
  constructor(x, y) {
    super(x, y, 22, 36);
    this.direction = 1;
  }

  update() {
    this.vx = 0;
    if (keyIsDown(LEFT_ARROW)) {
      this.vx = -3.5;
      this.direction = -1;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.vx = 3.5;
      this.direction = 1;
    }
    this.move();
  }

  jump() {
    if (this.onGround) {
      this.vy = -12.5;
    }
  }

  show() {
    // 歩いているときだけ、コマを進める
    let index = 0;
    if (this.vx !== 0) {
      index = floor(frameCount / 5) % 8;
    }
    if (this.onGround === false) {
      index = 2;
    }

    push();
    translate(this.x + this.w / 2, this.y + this.h / 2 - 4);
    scale(this.direction, 1);
    imageMode(CENTER);
    image(walkImage, 0, 0, 52, 52, index * 80, 0, 80, 80);
    pop();
  }
}

// 歩いて、壁や、足場の端で、向きを変える敵
class Walker extends Actor {
  constructor(x, y) {
    super(x, y, 30, 26);
    this.dir = -1;
    this.row = 1;
  }

  update() {
    this.vx = this.dir * 1.2;
    this.move();

    // 進む先の足元に、ブロックがなければ、引き返す
    let frontX = this.x + this.w / 2 + this.dir * (this.w / 2 + 2);
    if (this.blocked || (this.onGround && isSolid(frontX, this.y + this.h + 4) === false)) {
      this.dir = -this.dir;
    }
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    imageMode(CORNER);
    image(enemyImage, this.x - 9, this.y - 16, 48, 48, frame * 64, this.row * 64, 64, 64);
  }
}

// その場で、ときどき跳ねる敵
class Hopper extends Walker {
  constructor(x, y) {
    super(x, y);
    this.row = 3;
  }

  update() {
    this.vx = 0;
    if (this.onGround && frameCount % 90 === 0) {
      this.vy = -10;
    }
    this.move();
  }
}

1段ずつ、短くした足場を、重ねると、階段に、なります。いちばん上には、コインを、置きました。


ステージの形を変えるのに、当たり判定も、描画も、直していません。配列の値を、変えただけです。ステージが、データとして、プログラムから、切り離されているからです。

まとめ

  • ステージは、マスごとに値を持つ、二次元配列(タイルマップ)で作る。まとめて塗る関数があると、楽に組み立てられる
  • マスの番号、ワールド座標、画面座標の、3種類の座標がある。自機と敵の位置は、ワールド座標で持つ
  • 座標を、タイルの大きさで割って、切り捨てると、マスの番号になる。配列の外のときの答えを、先に決めておく
  • ブロックとの当たりは、横と縦を、別々に動かして、それぞれで、めり込みを調べ、ブロックの手前へ、押し戻す
  • 下へ動いて、床に当たったときに、「地面に立っている」と、記録する。ジャンプは、立っているときだけ
  • カメラは、描く位置を、ずらすだけ。当たり判定は、ワールド座標のまま、変えない
  • 重力とブロックとの当たりを、親クラスに書いておくと、自機も敵も、それを使い回せる
  • 敵を踏んだかどうかは、自機が落ちているか、足元が、敵の上のほうにあるかで、判定する
  • コインやゴールも、タイルの値にすると、配列を書き換えるだけで、取ったり、置いたりできる
  • 長いプログラムは、まとまりごとに、ファイルに分ける。親クラスのファイルを、先に読み込む