04.creating_the_enemy.rst 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. .. _doc_your_first_2d_game_creating_the_enemy:
  2. Creating the enemy
  3. ==================
  4. Now it's time to make the enemies our player will have to dodge. Their behavior
  5. will not be very complex: mobs will spawn randomly at the edges of the screen,
  6. choose a random direction, and move in a straight line.
  7. We'll create a ``Mob`` scene, which we can then *instance* to create any number
  8. of independent mobs in the game.
  9. Node setup
  10. ~~~~~~~~~~
  11. Click Scene -> New Scene from the top menu and add the following nodes:
  12. - :ref:`RigidBody2D <class_RigidBody2D>` (named ``Mob``)
  13. - :ref:`AnimatedSprite2D <class_AnimatedSprite2D>`
  14. - :ref:`CollisionShape2D <class_CollisionShape2D>`
  15. - :ref:`VisibleOnScreenNotifier2D <class_VisibleOnScreenNotifier2D>`
  16. Don't forget to set the children so they can't be selected, like you did with
  17. the Player scene.
  18. Select the ``Mob`` node and set its ``Gravity Scale``
  19. property in the :ref:`RigidBody2D <class_RigidBody2D>`
  20. section of the inspector to ``0``.
  21. This will prevent the mob from falling downwards.
  22. In addition, under the :ref:`CollisionObject2D <class_CollisionObject2D>`
  23. section just beneath the **RigidBody2D** section,
  24. expand the **Collision** group and
  25. uncheck the ``1`` inside the ``Mask`` property.
  26. This will ensure the mobs do not collide with each other.
  27. .. image:: img/set_collision_mask.webp
  28. Set up the :ref:`AnimatedSprite2D <class_AnimatedSprite2D>` like you did for the
  29. player. This time, we have 3 animations: ``fly``, ``swim``, and ``walk``. There
  30. are two images for each animation in the art folder.
  31. The ``Animation Speed`` property has to be set for each individual animation. Adjust it to ``3`` for all 3 animations.
  32. .. image:: img/mob_animations.webp
  33. You can use the "Play Animation" buttons on the right of the ``Animation Speed`` input field to preview your animations.
  34. We'll select one of these animations randomly so that the mobs will have some
  35. variety.
  36. Like the player images, these mob images need to be scaled down. Set the
  37. ``AnimatedSprite2D``'s ``Scale`` property to ``(0.75, 0.75)``.
  38. As in the ``Player`` scene, add a ``CapsuleShape2D`` for the collision. To align
  39. the shape with the image, you'll need to set the ``Rotation`` property
  40. to ``90`` (under "Transform" in the Inspector).
  41. Save the scene.
  42. Enemy script
  43. ~~~~~~~~~~~~
  44. Add a script to the ``Mob`` like this:
  45. .. tabs::
  46. .. code-tab:: gdscript GDScript
  47. extends RigidBody2D
  48. .. code-tab:: csharp
  49. using Godot;
  50. public partial class Mob : RigidBody2D
  51. {
  52. // Don't forget to rebuild the project.
  53. }
  54. Now let's look at the rest of the script. In ``_ready()`` we play the animation
  55. and randomly choose one of the three animation types:
  56. .. tabs::
  57. .. code-tab:: gdscript GDScript
  58. func _ready():
  59. var mob_types = $AnimatedSprite2D.sprite_frames.get_animation_names()
  60. $AnimatedSprite2D.play(mob_types[randi() % mob_types.size()])
  61. .. code-tab:: csharp
  62. public override void _Ready()
  63. {
  64. var animatedSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
  65. string[] mobTypes = animatedSprite2D.SpriteFrames.GetAnimationNames();
  66. animatedSprite2D.Play(mobTypes[GD.Randi() % mobTypes.Length]);
  67. }
  68. First, we get the list of animation names from the AnimatedSprite2D's ``sprite_frames``
  69. property. This returns an Array containing all three animation names: ``["walk",
  70. "swim", "fly"]``.
  71. We then need to pick a random number between ``0`` and ``2`` to select one of
  72. these names from the list (array indices start at ``0``). ``randi() % n``
  73. selects a random integer between ``0`` and ``n-1``.
  74. The last piece is to make the mobs delete themselves when they leave the screen.
  75. Connect the ``screen_exited()`` signal of the ``VisibleOnScreenNotifier2D`` node
  76. to the ``Mob`` and add this code:
  77. .. tabs::
  78. .. code-tab:: gdscript GDScript
  79. func _on_visible_on_screen_notifier_2d_screen_exited():
  80. queue_free()
  81. .. code-tab:: csharp
  82. // We also specified this function name in PascalCase in the editor's connection window.
  83. private void OnVisibleOnScreenNotifier2DScreenExited()
  84. {
  85. QueueFree();
  86. }
  87. This completes the `Mob` scene.
  88. With the player and enemies ready, in the next part, we'll bring them together
  89. in a new scene. We'll make enemies spawn randomly around the game board and move
  90. forward, turning our project into a playable game.