箱を用意する
ボールを受け止める「箱」(左右の壁と床)を描きます。ただしこの節では見た目を描くだけで、 まだ物理の当たり判定はありません。だからボールは箱をすり抜けて落ちていきます。
「まず見た目 → 次に当たり判定」と段階を分けるのは、絵と物理を別々に確認するためです。
今回さわる
game/:main.jsを書き換え
前の節を終えていない人は、ここから始められます。
箱の寸法をまとめる
Section titled “箱の寸法をまとめる”create の先頭に、箱の位置と太さを 1 か所にまとめておきます。あとで壁・床の座標計算に使い回します。
main.js を変更する
Section titled “main.js を変更する”99},1010scene: {1111 create: function () {12 const radius = 30;12 const box = {13 left: 60,14 right: 340,15 top: 150,16 bottom: 540,17 wall: 1218 };1319
14 const ball = this.add.circle(200, 100, radius, 0x333333);20 const g = this.add.graphics();21 g.fillStyle(0xe74c3c, 1);22 g.fillRect(box.left - box.wall, box.top, box.wall, box.bottom - box.top);1523
24 g.fillStyle(0x2ecc71, 1);25 g.fillRect(box.right, box.top, box.wall, box.bottom - box.top);26
27 g.fillStyle(0x3498db, 1);28 g.fillRect(box.left - box.wall, box.bottom, box.right - box.left + box.wall * 2, box.wall);29
30 const radius = 2531 const ball = this.add.circle(200, 80, radius, 0x333333);32
1633 this.matter.add.gameObject(ball, {1734 shape: {1835 type: 'circle',left/right… 内側の左右の位置top/bottom… 壁の上端・下端(床の高さ)wall… 壁と床の太さ
this.add.graphics() は「自由に図形を描くためのペン」です。色を決めて(fillStyle)、四角形を
塗る(fillRect)を繰り返して、左の壁・右の壁・床を描きます。
fillRect(x, y, 幅, 高さ) は左上を起点に四角を塗ります。壁は box の値から幅・高さを計算しているので、
box を変えれば箱全体の大きさが変わります。左右で色を変えているのは、後で「どちら側の壁か」を
目で追いやすくするためです。
ボールはそのまま
Section titled “ボールはそのまま”ボールを作る部分は前の節とほぼ同じです。半径を少し小さく(25)して、箱に入りやすくしておきます。
箱が表示され、ボールが落ちてきます。でも箱は絵だけなので、ボールは床をすり抜けて消えます。 次の節でこの壁と床に当たり判定を付けます。
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”game
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>03 箱を用意する(すり抜ける)</title> <style> body { margin: 0; display: grid; place-items: center; min-height: 100vh; background: #222; } canvas { display: block; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body></body></html>new Phaser.Game({ type: Phaser.AUTO, width: 400, height: 600, backgroundColor: '#fdf6e3', physics: { default: 'matter', matter: { gravity: { y: 1 } }, }, scene: { create: function () { const box = { left: 60, right: 340, top: 150, bottom: 540, wall: 12 };
const g = this.add.graphics(); g.fillStyle(0xe74c3c, 1); g.fillRect(box.left - box.wall, box.top, box.wall, box.bottom - box.top);
g.fillStyle(0x2ecc71, 1); g.fillRect(box.right, box.top, box.wall, box.bottom - box.top);
g.fillStyle(0x3498db, 1); g.fillRect(box.left - box.wall, box.bottom, box.right - box.left + box.wall * 2, box.wall);
const radius = 25 const ball = this.add.circle(200, 80, radius, 0x333333);
this.matter.add.gameObject(ball, { shape: { type: 'circle', radius: radius }, }); } },});