Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

建立內容

是時候來做一些讓玩家閃躲的敵人了。這些敵人的行為不會很複雜:怪物會隨機在螢幕的邊緣產生,接著隨機選一個方向來直線移動。

我們來建立一個 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.

../../_images/set_collision_mask.webp

接著像剛才設定玩家那樣,設定 AnimatedSprite 。這次有三種動畫: fly (飛行)、 swim (游泳) 與 walk (行走)。每個動畫都有兩個圖片,放在 art 資料夾中。

必須為每個單獨動畫設定 動畫速度 屬性,將三個動畫的對應動畫速度值都調整為 3

../../_images/mob_animations.webp

你可以使用 動畫速度 輸入區域右側的“播放動畫”按鈕預覽動畫。

接著我們會隨機選擇其中一個動畫來播放,這樣才不會讓所有怪物看起來都一樣。

就像玩家的圖片一樣,這些怪物的圖片也需要縮小。將 AnimatedSpriteScale (縮放) 屬性設為 (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).

保存場景。

敵人腳本

Mob 新增一個腳本,並新增下列成員變數:

extends RigidBody2D

現在來看看腳本剩下的部分。我們在 _ready() 中隨機在三種動畫中選擇一個:

func _ready():
    var mob_types = $AnimatedSprite2D.sprite_frames.get_animation_names()
    $AnimatedSprite2D.play(mob_types[randi() % mob_types.size()])

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"].

接著我們需要選擇 02 間的一個隨機數,用來從這個陣列中選擇名稱(陣列的索引從 0 開始)。 使用 randi() % n 可以從 0n - 1 之間隨機選擇一個整數。

最後我們來讓怪物在離開畫面後刪除自己。連接 VisibilityNotifier2D 節點的 screen_exited() 訊號,並新增這段程式碼:

func _on_visible_on_screen_notifier_2d_screen_exited():
    queue_free()

這樣就完成了 Mob 場景。

玩家和敵人已經準備就緒,接下來,我們將在一個新的場景中把他們放到一起。我們將使敵人在遊戲台上隨機生成並前進,我們的專案將變成一個能玩的遊戲。