SVGマスターへの道

付録B2: SVGシンプルシューターゲーム

この付録では、SVGとJavaScriptを使って、古典的なシューティングゲームの非常にシンプルなバージョンを作成します。自機を操作し、弾を発射して画面上部から現れる敵を撃ち落とすゲームです。このサンプルを通じて、キーボード入力の処理、複数のSVG要素の動的な生成・移動・削除、そして簡単な衝突判定といった、よりゲームらしいインタラクションの実装に触れてみましょう。

ゲームのルールと遊び方

シンプルシューター

スコア: 0 (操作: ← → で移動, Spaceで発射)
Press Start

使用した主なSVGとJavaScriptのテクニック

豆知識 (English/日本語)

Did you know? The `getBBox()` method in SVG returns the tightest bounding box around an element's geometry, excluding stroke width. If you need to include stroke in collision detection, you might need to adjust the bounding box dimensions manually or use more advanced techniques. Also, `getBBox()` results are in the element's local coordinate system if it has transformations; for global coordinates, `getBoundingClientRect()` might be more useful but needs conversion to SVG space.

知っていましたか?SVGの`getBBox()`メソッドは、要素のジオメトリ(線の太さは除く)を囲む最小のバウンディングボックスを返します。衝突判定に線の太さを含めたい場合は、バウンディングボックスの寸法を手動で調整するか、より高度なテクニックを使う必要があるかもしれません。また、`getBBox()`の結果は、要素に変形が適用されている場合、その要素のローカル座標系での値になります。グローバル座標が必要な場合は `getBoundingClientRect()` の方が役立つかもしれませんが、SVG座標空間への変換が必要です。

まとめ

このシューティングゲームのサンプルは、SVGでどこまでゲーム的な要素を実装できるかの一例です。より複雑なゲームには専門のエンジンが適していますが、SVGでもアイデア次第で楽しいインタラクティブコンテンツが作れますね。

次は、付録の最後のゲーム「付録B3: テキストアドベンチャー風ゲーム」で、SVGを使った物語体験に挑戦しましょう。

このページの要約

日本語

このページでは、SVGとJavaScriptを使ったシンプルなシューティングゲームの作り方を紹介しました。プレイヤーはキーボードで自機を操作し、弾を発射して敵を撃ちます。敵は画面上部から出現し下に移動します。弾と敵の衝突判定は各SVG要素のgetBBox()メソッドで得られるバウンディングボックスの重なりで判定します。ゲームの進行はrequestAnimationFrameによるゲームループで管理し、SVG要素の属性を動的に変更することでオブジェクトの移動や生成・削除を行っています。

English

This page introduced how to create a simple shooter game using SVG and JavaScript. The player controls a ship via the keyboard, firing bullets to shoot enemies that appear from the top of the screen and move downwards. Collision detection between bullets and enemies is determined by overlapping bounding boxes obtained using the getBBox() method of SVG elements. Game progression is managed by a game loop using requestAnimationFrame, dynamically changing SVG element attributes for object movement, creation, and deletion.

Español

Esta página introdujo cómo crear un juego de disparos simple usando SVG y JavaScript. El jugador controla una nave mediante el teclado, disparando balas para derribar enemigos que aparecen desde la parte superior de la pantalla y se mueven hacia abajo. La detección de colisiones entre balas y enemigos se determina mediante la superposición de cuadros delimitadores obtenidos con el método getBBox() de los elementos SVG. La progresión del juego se gestiona mediante un bucle de juego que utiliza requestAnimationFrame, cambiando dinámicamente los atributos de los elementos SVG para el movimiento, creación y eliminación de objetos.

中文

本页介绍了如何使用SVG和JavaScript创建一个简单的射击游戏。玩家通过键盘控制飞船,发射子弹射击从屏幕顶部出现并向下移动的敌人。子弹和敌人之间的碰撞检测是通过SVG元素的getBBox()方法获得的边界框是否重叠来确定的。游戏进程由使用requestAnimationFrame的游戏循环管理,通过动态更改SVG元素属性来实现对象的移动、创建和删除。