Creating the enemy¶
Now it's time to make the enemies our player will have to dodge. Their behavior will not be very complex: mobs will spawn randomly at the edges of the screen, choose a random direction, and move in a straight line.
We'll create a
Mob scene, which we can then instance to create any number
of independent mobs in the game.
Click Scene -> New Scene and add the following nodes:
Don't forget to set the children so they can't be selected, like you did with the Player scene.
In the RigidBody2D properties, set
0, so the mob will not fall downward. In addition, under the
PhysicsBody2D section, click the
Mask property and uncheck the first
box. This will ensure the mobs do not collide with each other.
Set up the AnimatedSprite like you did for the
player. This time, we have 3 animations:
are two images for each animation in the art folder.
Adjust the "Speed (FPS)" to
3 for all animations.
Playing property in the Inspector to "On".
We'll select one of these animations randomly so that the mobs will have some variety.
Like the player images, these mob images need to be scaled down. Set the
Scale property to
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 Degrees property
90 (under "Transform" in the Inspector).
Save the scene.
Add a script to the
Mob and add the following member variables:
When we spawn a mob, we'll pick a random value between
max_speed for how fast each mob will move (it would be boring if they were
all moving at the same speed).
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:
First, we get the list of animation names from the AnimatedSprite's
property. This returns an Array containing all three animation names:
We then need to pick a random number between
2 to select one of
these names from the list (array indices start at
randi() % n
selects a random integer between
You must use
randomize() if you want your sequence of "random"
numbers to be different every time you run the scene. We're going to
randomize() in our
Main scene, so we won't need it here.
The last piece is to make the mobs delete themselves when they leave the screen.
screen_exited() signal of the
VisibilityNotifier2D node and
add this code:
This completes the Mob scene.
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.