Creating the enemy¶
이제 우리의 플레이어가 피할 몹을 만들 차례입니다. 이들의 행동은 그리 복잡하진 않을 것입니다: 몹이 아무렇게나 화면의 가장자리에서 나타나고 무작위 방향을 선택해 직선으로 이동합니다.
먼저 Mob
장면을 생성할 것입니다. 그런 다음 인스턴스화해서 게임에서 원하는 수의 독립적인 몹을 생성할 수 있습니다.
노드 설정하기¶
씬(Scene) -> 새 씬(New Scene)을 클릭 후 다음 노드들을 추가하세요:
RigidBody2D (
Mob
으로 이름지음)VisibilityNotifier2D (
Visibility
로 이름지음)
플레이어 씬에서 한 것과 마찬가지로, 자식이 선택되지 않도록 설정하는 것을 잊지마세요.
In the RigidBody2D properties, set Gravity Scale
to 0
, so the mob will not fall downward. In addition, under the
CollisionObject2D section, click the Mask
property and uncheck the first
box. This will ensure the mobs do not collide with each other.

플레이어에서 설정한 것처럼 AnimatedSprite를 설정합니다. 이번에는 fly
, swim
, walk
의 3가지 애니메이션이 있습니다. art 폴더에는 각 애니메이션에 대해 두 개의 이미지가 있습니다.
모든 애니메이션의 "속도(FPS)"를 3
으로 조정하세요.

Set the Playing
property in the Inspector to "On".
몬스터가 다양해질 수 있도록 이 애니메이션 중 하나를 무작위로 선택할 것입니다.
Like the player images, these mob images need to be scaled down. Set the
AnimatedSprite
's Scale
property to (0.75, 0.75)
.
Player
씬처럼 콜리전을 위한 CapsuleShape2D
을 추가하세요. 이미지와 모양이 같도록, Node2D
아래 Rotation Degrees
속성을 90
으로 설정해야 합니다(인스펙터(Inspector)의 "Transform" 아래에 있음).
씬을 저장하세요.
적 스크립트¶
Add a script to the Mob
like this:
extends RigidBody2D
public class Mob : RigidBody2D
{
// Don't forget to rebuild the project.
}
// Copy `player.gdns` to `mob.gdns` and replace `Player` with `Mob`.
// Attach the `mob.gdns` file to the Mob node.
// Create two files `mob.cpp` and `mob.hpp` next to `entry.cpp` in `src`.
// This code goes in `mob.hpp`. We also define the methods we'll be using here.
#ifndef MOB_H
#define MOB_H
#include <AnimatedSprite.hpp>
#include <Godot.hpp>
#include <RigidBody2D.hpp>
class Mob : public godot::RigidBody2D {
GODOT_CLASS(Mob, godot::RigidBody2D)
godot::AnimatedSprite *_animated_sprite;
public:
void _init() {}
void _ready();
void _on_VisibilityNotifier2D_screen_exited();
static void _register_methods();
};
#endif // MOB_H
Now let's look at the rest of the script. In _ready()
we play the animation
and randomly choose one of the three animation types:
func _ready():
$AnimatedSprite.playing = true
var mob_types = $AnimatedSprite.frames.get_animation_names()
$AnimatedSprite.animation = mob_types[randi() % mob_types.size()]
public override void _Ready()
{
var animSprite = GetNode<AnimatedSprite>("AnimatedSprite");
animSprite.Playing = true;
string[] mobTypes = animSprite.Frames.GetAnimationNames();
animSprite.Animation = mobTypes[GD.Randi() % mobTypes.Length];
}
// This code goes in `mob.cpp`.
#include "mob.hpp"
#include <RandomNumberGenerator.hpp>
#include <SpriteFrames.hpp>
void Mob::_ready() {
godot::Ref<godot::RandomNumberGenerator> random = godot::RandomNumberGenerator::_new();
random->randomize();
_animated_sprite = get_node<godot::AnimatedSprite>("AnimatedSprite");
_animated_sprite->_set_playing(true);
godot::PoolStringArray mob_types = _animated_sprite->get_sprite_frames()->get_animation_names();
_animated_sprite->set_animation(mob_types[random->randi() % mob_types.size()]);
}
First, we get the list of animation names from the AnimatedSprite's frames
property. This returns an Array containing all three animation names: ["walk",
"swim", "fly"]
.
그런 다음 목록에서 이 이름 중 하나를 선택하려면 0
과 2
사이의 임의의 숫자를 선택해야 합니다(배열 인덱스는 0
에서 시작). randi() % n
은 0
과 n-1
사이의 임의의 정수를 선택합니다.
참고
씬을 실행할 때 매 순간마다 "무작위" 숫자 배열이 다르기를 원한다면 randomize()
를 사용해야 합니다. randomize()
를 Main
씬에서 사용할 것이기 때문에 여기서는 필요하지 않습니다.
마지막 과정은 몹이 화면을 떠날 때 스스로 삭제하도록 하는 것입니다. VisibilityNotifier2D
노드의 screen_exited()
시그널을 연결하고 다음 코드를 추가합니다:
func _on_VisibilityNotifier2D_screen_exited():
queue_free()
public void OnVisibilityNotifier2DScreenExited()
{
QueueFree();
}
// This code goes in `mob.cpp`.
void Mob::_on_VisibilityNotifier2D_screen_exited() {
queue_free();
}
이것으로 Mob 씬이 완성되었습니다.
With the player and enemies ready, in the next part, we'll bring them together in a new scene. We'll make enemies spawn randomly around the game board and move forward, turning our project into a playable game.