Designing the mob scene

In this part, you’re going to code the monsters, which we’ll call mobs. In the next lesson, we’ll spawn them randomly around the playable area.

Let’s design the monsters themselves in a new scene. The node structure is going to be similar to the player.tscn scene.

Create a scene with, once again, a CharacterBody3D node as its root. Name it Mob. Add a child node Node3D, name it Pivot. And drag and drop the file mob.glb from the FileSystem dock onto the Pivot to add the monster’s 3D model to the scene.

../../_images/drag_drop_mob.webp

You can rename the newly created mob node into Character.

image0

We need a collision shape for our body to work. Right-click on the Mob node, the scene’s root, and click Add Child Node.

image1

Add a CollisionShape3D.

image2

In the Inspector, assign a BoxShape3D to the Shape property.

../../_images/08.create_box_shape3D.jpg

We should change its size to fit the 3D model better. You can do so interactively by clicking and dragging on the orange dots.

The box should touch the floor and be a little thinner than the model. Physics engines work in such a way that if the player’s sphere touches even the box’s corner, a collision will occur. If the box is a little too big compared to the 3D model, you may die at a distance from the monster, and the game will feel unfair to the players.

image4

Notice that my box is taller than the monster. It is okay in this game because we’re looking at the scene from above and using a fixed perspective. Collision shapes don’t have to match the model exactly. It’s the way the game feels when you test it that should dictate their form and size.

Removing monsters off-screen

We’re going to spawn monsters at regular time intervals in the game level. If we’re not careful, their count could increase to infinity, and we don’t want that. Each mob instance has both a memory and a processing cost, and we don’t want to pay for it when the mob is outside the screen.

Once a monster leaves the screen, we don’t need it anymore, so we should delete it. Godot has a node that detects when objects leave the screen, VisibleOnScreenNotifier3D, and we’re going to use it to destroy our mobs.

Note

When you keep instancing an object, there’s a technique you can use to avoid the cost of creating and destroying instances all the time called pooling. It consists of pre-creating an array of objects and reusing them over and over.

When working with GDScript, you don’t need to worry about this. The main reason to use pools is to avoid freezes with garbage-collected languages like C# or Lua. GDScript uses a different technique to manage memory, reference counting, which doesn’t have that caveat. You can learn more about that here: Memory management.

Select the Mob node and add a child node VisibleOnScreenNotifier3D. Another box, pink this time, appears. When this box completely leaves the screen, the node will emit a signal.

image5

Resize it using the orange dots until it covers the entire 3D model.

image6

Coding the mob’s movement

Let’s implement the monster’s motion. We’re going to do this in two steps. First, we’ll write a script on the Mob that defines a function to initialize the monster. We’ll then code the randomized spawn mechanism in the main.tscn scene and call the function from there.

Attach a script to the Mob.

image7

Here’s the movement code to start with. We define two properties, min_speed and max_speed, to define a random speed range, which we will later use to define CharacterBody3D.velocity.

GDScriptC#

  1. extends CharacterBody3D
  2. # Minimum speed of the mob in meters per second.
  3. @export var min_speed = 10
  4. # Maximum speed of the mob in meters per second.
  5. @export var max_speed = 18
  6. func _physics_process(_delta):
  7. move_and_slide()
  1. using Godot;
  2. public partial class Mob : CharacterBody3D
  3. {
  4. // Don't forget to rebuild the project so the editor knows about the new export variable.
  5. // Minimum speed of the mob in meters per second
  6. [Export]
  7. public int MinSpeed { get; set; } = 10;
  8. // Maximum speed of the mob in meters per second
  9. [Export]
  10. public int MaxSpeed { get; set; } = 18;
  11. public override void _PhysicsProcess(double delta)
  12. {
  13. MoveAndSlide();
  14. }
  15. }

Similarly to the player, we move the mob every frame by calling the function CharacterBody3D.move_and_slide(). This time, we don’t update the velocity every frame; we want the monster to move at a constant speed and leave the screen, even if it were to hit an obstacle.

We need to define another function to calculate the CharacterBody3D.velocity. This function will turn the monster towards the player and randomize both its angle of motion and its velocity.

The function will take a start_position,the mob’s spawn position, and the player_position as its arguments.

We position the mob at start_position and turn it towards the player using the look_at_from_position() method, and randomize the angle by rotating a random amount around the Y axis. Below, randf_range() outputs a random value between -PI / 4 radians and PI / 4 radians.

GDScriptC#

  1. # This function will be called from the Main scene.
  2. func initialize(start_position, player_position):
  3. # We position the mob by placing it at start_position
  4. # and rotate it towards player_position, so it looks at the player.
  5. look_at_from_position(start_position, player_position, Vector3.UP)
  6. # Rotate this mob randomly within range of -45 and +45 degrees,
  7. # so that it doesn't move directly towards the player.
  8. rotate_y(randf_range(-PI / 4, PI / 4))
  1. // This function will be called from the Main scene.
  2. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  3. {
  4. // We position the mob by placing it at startPosition
  5. // and rotate it towards playerPosition, so it looks at the player.
  6. LookAtFromPosition(startPosition, playerPosition, Vector3.Up);
  7. // Rotate this mob randomly within range of -45 and +45 degrees,
  8. // so that it doesn't move directly towards the player.
  9. RotateY((float)GD.RandRange(-Mathf.Pi / 4.0, Mathf.Pi / 4.0));
  10. }

We got a random position, now we need a random_speed. randi_range() will be useful as it gives random int values, and we will use min_speed and max_speed. random_speed is just an integer, and we just use it to multiply our CharacterBody3D.velocity. After random_speed is applied, we rotate CharacterBody3D.velocity Vector3 towards the player.

GDScriptC#

  1. func initialize(start_position, player_position):
  2. # ...
  3. # We calculate a random speed (integer)
  4. var random_speed = randi_range(min_speed, max_speed)
  5. # We calculate a forward velocity that represents the speed.
  6. velocity = Vector3.FORWARD * random_speed
  7. # We then rotate the velocity vector based on the mob's Y rotation
  8. # in order to move in the direction the mob is looking.
  9. velocity = velocity.rotated(Vector3.UP, rotation.y)
  1. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  2. {
  3. // ...
  4. // We calculate a random speed (integer).
  5. int randomSpeed = GD.RandRange(MinSpeed, MaxSpeed);
  6. // We calculate a forward velocity that represents the speed.
  7. Velocity = Vector3.Forward * randomSpeed;
  8. // We then rotate the velocity vector based on the mob's Y rotation
  9. // in order to move in the direction the mob is looking.
  10. Velocity = Velocity.Rotated(Vector3.Up, Rotation.Y);
  11. }

Leaving the screen

We still have to destroy the mobs when they leave the screen. To do so, we’ll connect our VisibleOnScreenNotifier3D node’s screen_exited signal to the Mob.

Head back to the 3D viewport by clicking on the 3D label at the top of the editor. You can also press Ctrl + F2 (Opt + 2 on macOS).

image8

Select the VisibleOnScreenNotifier3D node and on the right side of the interface, navigate to the Node dock. Double-click the screen_exited() signal.

image9

Connect the signal to the Mob

image10

This will add a new function for you in your mob script, _on_visible_on_screen_notifier_3d_screen_exited(). From it, call the queue_free() method. This function destroys the instance it’s called on.

GDScriptC#

  1. func _on_visible_on_screen_notifier_3d_screen_exited():
  2. queue_free()
  1. // We also specified this function name in PascalCase in the editor's connection window.
  2. private void OnVisibilityNotifierScreenExited()
  3. {
  4. QueueFree();
  5. }

Our monster is ready to enter the game! In the next part, you will spawn monsters in the game level.

Here is the complete mob.gd script for reference.

GDScriptC#

  1. extends CharacterBody3D
  2. # Minimum speed of the mob in meters per second.
  3. @export var min_speed = 10
  4. # Maximum speed of the mob in meters per second.
  5. @export var max_speed = 18
  6. func _physics_process(_delta):
  7. move_and_slide()
  8. # This function will be called from the Main scene.
  9. func initialize(start_position, player_position):
  10. # We position the mob by placing it at start_position
  11. # and rotate it towards player_position, so it looks at the player.
  12. look_at_from_position(start_position, player_position, Vector3.UP)
  13. # Rotate this mob randomly within range of -45 and +45 degrees,
  14. # so that it doesn't move directly towards the player.
  15. rotate_y(randf_range(-PI / 4, PI / 4))
  16. # We calculate a random speed (integer)
  17. var random_speed = randi_range(min_speed, max_speed)
  18. # We calculate a forward velocity that represents the speed.
  19. velocity = Vector3.FORWARD * random_speed
  20. # We then rotate the velocity vector based on the mob's Y rotation
  21. # in order to move in the direction the mob is looking.
  22. velocity = velocity.rotated(Vector3.UP, rotation.y)
  23. func _on_visible_on_screen_notifier_3d_screen_exited():
  24. queue_free()
  1. using Godot;
  2. public partial class Mob : CharacterBody3D
  3. {
  4. // Minimum speed of the mob in meters per second.
  5. [Export]
  6. public int MinSpeed { get; set; } = 10;
  7. // Maximum speed of the mob in meters per second.
  8. [Export]
  9. public int MaxSpeed { get; set; } = 18;
  10. public override void _PhysicsProcess(double delta)
  11. {
  12. MoveAndSlide();
  13. }
  14. // This function will be called from the Main scene.
  15. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  16. {
  17. // We position the mob by placing it at startPosition
  18. // and rotate it towards playerPosition, so it looks at the player.
  19. LookAtFromPosition(startPosition, playerPosition, Vector3.Up);
  20. // Rotate this mob randomly within range of -45 and +45 degrees,
  21. // so that it doesn't move directly towards the player.
  22. RotateY((float)GD.RandRange(-Mathf.Pi / 4.0, Mathf.Pi / 4.0));
  23. // We calculate a random speed (integer).
  24. int randomSpeed = GD.RandRange(MinSpeed, MaxSpeed);
  25. // We calculate a forward velocity that represents the speed.
  26. Velocity = Vector3.Forward * randomSpeed;
  27. // We then rotate the velocity vector based on the mob's Y rotation
  28. // in order to move in the direction the mob is looking.
  29. Velocity = Velocity.Rotated(Vector3.Up, Rotation.Y);
  30. }
  31. // We also specified this function name in PascalCase in the editor's connection window.
  32. private void OnVisibilityNotifierScreenExited()
  33. {
  34. QueueFree();
  35. }
  36. }

User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next