Up to date
This page is up to date for Godot 4.2
.
If you still find outdated information, please open an issue.
敵の作成¶
次はプレイヤーが避けるべき敵を作りましょう。敵の行動はあまり複雑ではありません。モブは画面の端でランダムに生まれると、ランダムな方向を選び、一直線に進みます。
これから Mob
シーンを作り、それをインスタンス化して、ゲーム内に任意の数の独立したモブを作成します。
ノードの設定¶
トップメニューから [シーン → 新規シーン] をクリックして、次のノードを追加します:
RigidBody2D(
Mob
という名前)
Playerシーンと同様に、選択できないように子を設定することを忘れないでください。
Select the Mob
node and set it's Gravity Scale
property in the RigidBody2D
section of the inspector to 0
.
This will prevent the mob from falling downwards.
In addition, under the CollisionObject2D
section just beneath the RigidBody2D section,
expand the Collision group and
uncheck the 1
inside the Mask
property.
This will ensure the mobs do not collide with each other.
プレイヤーと同じように AnimatedSprite2D を設定します。 今回は、3つのアニメーションがあります: fly
、swim
、walk
です。 artフォルダ内には、各アニメーション用の画像が2枚ずつ入っています。
Animation Speed
プロパティは、アニメーションごとに設定する必要があります。3つのアニメーションすべてに対して 3
を設定します。
Animation Speed
入力フィールドの右側にある「▶」ボタンを使って、アニメーションをプレビューすることができます。
モブにバラエティを持たせるために、1つのアニメーションをランダムに選択します。
プレイヤーの画像と同じように、モブの画像も小さくする必要があります。 AnimatedSprite2D
の Scale
プロパティを (0.75, 0.75)
に設定します。
As in the Player
scene, add a CapsuleShape2D
for the collision. To align
the shape with the image, you'll need to set the Rotation
property
to 90
(under "Transform" in the Inspector).
シーンを保存します。
Enemyスクリプト¶
以下のように``Mob`` にスクリプトを追加します。:
extends RigidBody2D
using Godot;
public partial class Mob : RigidBody2D
{
// Don't forget to rebuild the project.
}
それでは、スクリプトの残りの部分を見てみましょう。 _ready()
では、アニメーションを再生し、3つのアニメーションタイプのいずれかをランダムに選択します:
func _ready():
var mob_types = $AnimatedSprite2D.sprite_frames.get_animation_names()
$AnimatedSprite2D.play(mob_types[randi() % mob_types.size()])
public override void _Ready()
{
var animatedSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
string[] mobTypes = animatedSprite2D.SpriteFrames.GetAnimationNames();
animatedSprite2D.Play(mobTypes[GD.Randi() % mobTypes.Length]);
}
First, we get the list of animation names from the AnimatedSprite2D's sprite_frames
property. This returns an Array containing all three animation names: ["walk",
"swim", "fly"]
.
次に、 0
から 2
の間の乱数を選んで、リストから名前を選ぶ必要があります (配列のインデックスは 0
から始まります)。 randi() % n
は 0
から n-1
の間の乱数を選びます。
最後のピースは、モブが画面を離れたときにモブ自身を削除することです。 VisibleOnScreenNotifier2D
ノードの screen_exited()
シグナルを接続し、次のコードを追加します:
func _on_visible_on_screen_notifier_2d_screen_exited():
queue_free()
private void OnVisibleOnScreenNotifier2DScreenExited()
{
QueueFree();
}
これで Mob シーンが完成します。
プレイヤーと敵が準備できたので、次のパートではそれらを新しいシーンでまとめます。ランダムに敵が出現、まっすぐ動くようにし、プロジェクトを遊べるゲームにします。