Up to date

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

Створення ворога

Тепер настав час зробити ворогів, від яких гравцеві доведеться ухилятися. Їх поведінка буде не дуже складною: вони будуть час від часу виникати по краях екрана і рухатися у випадковому напрямку по прямій лінії.

Ми створимо сцену Mob, яку ми зможемо потім використати, для створення будь-якої кількості незалежних мобів в грі.

Налаштування вузлів

Click Scene -> New Scene from the top menu and add the following nodes:

Не забудьте налаштувати нащадків, щоб вони не могли бути обрані, як ви робили це зі сценою гравця.

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

Set up the AnimatedSprite2D like you did for the player. This time, we have 3 animations: fly, swim, and walk. There are two images for each animation in the art folder.

The Animation Speed property has to be set for each individual animation. Adjust it to 3 for all 3 animations.

../../_images/mob_animations.webp

You can use the "Play Animation" buttons on the right of the Animation Speed input field to preview your animations.

Ми вибиратимемо одну з цих анімації випадковим чином, тому моби будуть мати певну різноманітність.

Like the player images, these mob images need to be scaled down. Set the AnimatedSprite2D's Scale property to (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"].

Далі нам потрібно вибрати випадкове число між 0 та 2, щоб вибрати назву однієї з цих анімацій (массив індексується з 0). randi() % n вибирає випадкове ціле число між 0 та n-1.

The last piece is to make the mobs delete themselves when they leave the screen. Connect the screen_exited() signal of the VisibleOnScreenNotifier2D node to the Mob and add this code:

func _on_visible_on_screen_notifier_2d_screen_exited():
    queue_free()

На цьому завершуємо сцену Mob.

З гравцем і ворогами закінчено, в наступній частині ми об'єднаємо їх у новій сцені. Ми змусимо ворогів випадковим чином виникати навколо ігрової дошки і рухатися вперед, перетворюючи наш проект в гру.