![見出し画像](https://assets.st-note.com/production/uploads/images/166483267/rectangle_large_type_2_ca09edc445e90e0c9e2abd8c3ffae8ab.png?width=1200)
Photo by
shinsukesugie
Phaser.jsでの当たり判定
プログラミングを学べるゲーム開発も進捗し、Tiledで設定したマップがゲーム画面上に描画され、かつTiledで設定していた当たり判定もうまく操作させる予定のプレイヤーとの判定ができるようになり、いい感じです。
![](https://assets.st-note.com/img/1734678279-fRvr3nsZygzA2NoxJGC8Pt14.png?width=1200)
Phaser.js自体の日本語情報は結構豊富にあるイメージでしたが、Tiledを組み合わせた時の当たり判定のインポートの方法は日本語の情報が少ないのかなという印象で公式のドキュメント、サンプルが参考になりました。
どれくらいの方に参考になるのか分かりませんが、ClojureScriptでその当たり判定と当たり判定の部分を見やすく描画しているコードはこんな感じです。
(sc/create-layer! map "Background" spa-tileset {:scale scale :offset [(* 80 1) (+ 180 (* 3 3))]})
(let [_ground (sc/create-layer! map "Ground" spa-tileset {:scale scale :offset [(* 80 1) 180]})]
(.setCollisionFromCollisionGroup _ground)
(let [graphics (.graphics (.-add this))]
(.forEachTile
_ground
(fn [tile]
(let [tile-world-pos (.tileToWorldXY _ground (.-x tile) (.-y tile))
[tileset] (-> tile .-tilemapLayer .-tileset)
collision-group (.getTileCollisionGroup tileset (.-index tile))]
(when (and collision-group (> (count (.-objects collision-group)) 0))
(if (and (.-properties collision-group)
(-> collision-group .-properties .-isInteractive))
(.lineStyle graphics 5, 0x00ff00, 1)
(.lineStyle graphics 5, 0x00ffff, 1))
(doseq [object (.-objects collision-group)]
(let [x (+ (.-x tile-world-pos) (* (.-x object) scale))
y (+ (.-y tile-world-pos) (* (.-y object) scale))]
(cond
(.-rectangle object) (.strokeRect graphics x, y, (* (.-width object) scale) (* (.-height object) scale)))
(prn [x]))))))))
(reset! ground _ground))
ClojureScriptからPhaser.jsを操作する際には、ClojureScript用のライブラリを使っているという訳ではないので上記のように直接Phaser.jsのライブラリを触ってAPIにどういったものがあるか確認してから、おおよそ使い方がわかった段でプロジェクトの中のPhaser.jsを閉じ込めているそうに引っ越し作業を行うという手順で開発を進めています。
こうすることで次のゲームを作る場合にサブセットなライブラリの部分という形でPhaser.jsを操作できる、ゲームのコアの部分ではそのPhaser.jsであることの癖みたいなものを関心から分離できるというメリットがあります。
といった形でマップをTiledで作成し、それをゲーム内に持って来れる、かつ当たり判定も懸念がなくなったので、次はこのゲームの肝であるビジュアルプログラミング部分の実装を着手していこうと思う今日この頃です。