07.killing_player.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. :article_outdated: True
  2. .. _doc_first_3d_game_killing_the_player:
  3. Killing the player
  4. ==================
  5. We can kill enemies by jumping on them, but the player still can't die.
  6. Let's fix this.
  7. We want to detect being hit by an enemy differently from squashing them.
  8. We want the player to die when they're moving on the floor, but not if
  9. they're in the air. We could use vector math to distinguish the two
  10. kinds of collisions. Instead, though, we will use an :ref:`Area3D <class_Area3D>` node, which
  11. works well for hitboxes.
  12. Hitbox with the Area node
  13. -------------------------
  14. Head back to the ``player.tscn`` scene and add a new child node :ref:`Area3D <class_Area3D>`. Name it
  15. ``MobDetector``
  16. Add a :ref:`CollisionShape3D <class_CollisionShape3D>` node as a child of it.
  17. |image0|
  18. In the *Inspector*, assign a cylinder shape to it.
  19. |image1|
  20. Here is a trick you can use to make the collisions only happen when the
  21. player is on the ground or close to it. You can reduce the cylinder's
  22. height and move it up to the top of the character. This way, when the
  23. player jumps, the shape will be too high up for the enemies to collide
  24. with it.
  25. |image2|
  26. You also want the cylinder to be wider than the sphere. This way, the
  27. player gets hit before colliding and being pushed on top of the
  28. monster's collision box.
  29. The wider the cylinder, the more easily the player will get killed.
  30. Next, select the ``MobDetector`` node again, and in the *Inspector*, turn
  31. **off** its *Monitorable* property. This makes it so other physics nodes
  32. cannot detect the area. The complementary *Monitoring* property allows
  33. it to detect collisions. Then, remove the *Collision -> Layer* and set
  34. the mask to the "enemies" layer.
  35. |image3|
  36. When areas detect a collision, they emit signals. We're going to connect
  37. one to the ``Player`` node. Select ``MobDetector`` and go to *Inspector*'s *Node* tab, double-click the
  38. ``body_entered`` signal and connect it to the ``Player``
  39. |image4|
  40. The *MobDetector* will emit ``body_entered`` when a :ref:`CharacterBody3D <class_CharacterBody3D>` or a
  41. :ref:`RigidBody3D <class_RigidBody3D>` node enters it. As it only masks the "enemies" physics
  42. layers, it will only detect the ``Mob`` nodes.
  43. Code-wise, we're going to do two things: emit a signal we'll later use
  44. to end the game and destroy the player. We can wrap these operations in
  45. a ``die()`` function that helps us put a descriptive label on the code.
  46. .. tabs::
  47. .. code-tab:: gdscript GDScript
  48. # Emitted when the player was hit by a mob.
  49. # Put this at the top of the script.
  50. signal hit
  51. # And this function at the bottom.
  52. func die():
  53. hit.emit()
  54. queue_free()
  55. func _on_mob_detector_body_entered(body):
  56. die()
  57. .. code-tab:: csharp
  58. // Don't forget to rebuild the project so the editor knows about the new signal.
  59. // Emitted when the player was hit by a mob.
  60. [Signal]
  61. public delegate void HitEventHandler();
  62. // ...
  63. private void Die()
  64. {
  65. EmitSignal(SignalName.Hit);
  66. QueueFree();
  67. }
  68. // We also specified this function name in PascalCase in the editor's connection window
  69. private void OnMobDetectorBodyEntered(Node3D body)
  70. {
  71. Die();
  72. }
  73. Try the game again by pressing :kbd:`F5`. If everything is set up correctly,
  74. the character should die when an enemy runs into the collider. Note that without a ``Player``, the following line
  75. .. tabs::
  76. .. code-tab:: gdscript GDScript
  77. var player_position = $Player.position
  78. .. code-tab:: csharp
  79. Vector3 playerPosition = GetNode<Player>("Player").Position;
  80. gives error because there is no $Player!
  81. Also note that the enemy colliding with the player and dying depends on the size and position of the
  82. ``Player`` and the ``Mob``\ 's collision shapes. You may need to move them
  83. and resize them to achieve a tight game feel.
  84. Ending the game
  85. ---------------
  86. We can use the ``Player``\ 's ``hit`` signal to end the game. All we need
  87. to do is connect it to the ``Main`` node and stop the ``MobTimer`` in
  88. reaction.
  89. Open ``main.tscn``, select the ``Player`` node, and in the *Node* dock,
  90. connect its ``hit`` signal to the ``Main`` node.
  91. |image5|
  92. Get the timer, and stop it, in the ``_on_player_hit()`` function.
  93. .. tabs::
  94. .. code-tab:: gdscript GDScript
  95. func _on_player_hit():
  96. $MobTimer.stop()
  97. .. code-tab:: csharp
  98. // We also specified this function name in PascalCase in the editor's connection window
  99. private void OnPlayerHit()
  100. {
  101. GetNode<Timer>("MobTimer").Stop();
  102. }
  103. If you try the game now, the monsters will stop spawning when you die,
  104. and the remaining ones will leave the screen.
  105. You can pat yourself in the back: you prototyped a complete 3D game,
  106. even if it's still a bit rough.
  107. From there, we'll add a score, the option to retry the game, and you'll
  108. see how you can make the game feel much more alive with minimalistic
  109. animations.
  110. Code checkpoint
  111. ---------------
  112. Here are the complete scripts for the ``Main``, ``Mob``, and ``Player`` nodes,
  113. for reference. You can use them to compare and check your code.
  114. Starting with ``main.gd``.
  115. .. tabs::
  116. .. code-tab:: gdscript GDScript
  117. extends Node
  118. @export var mob_scene: PackedScene
  119. func _on_mob_timer_timeout():
  120. # Create a new instance of the Mob scene.
  121. var mob = mob_scene.instantiate()
  122. # Choose a random location on the SpawnPath.
  123. # We store the reference to the SpawnLocation node.
  124. var mob_spawn_location = get_node("SpawnPath/SpawnLocation")
  125. # And give it a random offset.
  126. mob_spawn_location.progress_ratio = randf()
  127. var player_position = $Player.position
  128. mob.initialize(mob_spawn_location.position, player_position)
  129. # Spawn the mob by adding it to the Main scene.
  130. add_child(mob)
  131. func _on_player_hit():
  132. $MobTimer.stop()
  133. .. code-tab:: csharp
  134. using Godot;
  135. public partial class Main : Node
  136. {
  137. [Export]
  138. public PackedScene MobScene { get; set; }
  139. private void OnMobTimerTimeout()
  140. {
  141. // Create a new instance of the Mob scene.
  142. Mob mob = MobScene.Instantiate<Mob>();
  143. // Choose a random location on the SpawnPath.
  144. // We store the reference to the SpawnLocation node.
  145. var mobSpawnLocation = GetNode<PathFollow3D>("SpawnPath/SpawnLocation");
  146. // And give it a random offset.
  147. mobSpawnLocation.ProgressRatio = GD.Randf();
  148. Vector3 playerPosition = GetNode<Player>("Player").Position;
  149. mob.Initialize(mobSpawnLocation.Position, playerPosition);
  150. // Spawn the mob by adding it to the Main scene.
  151. AddChild(mob);
  152. }
  153. private void OnPlayerHit()
  154. {
  155. GetNode<Timer>("MobTimer").Stop();
  156. }
  157. }
  158. Next is ``Mob.gd``.
  159. .. tabs::
  160. .. code-tab:: gdscript GDScript
  161. extends CharacterBody3D
  162. # Minimum speed of the mob in meters per second.
  163. @export var min_speed = 10
  164. # Maximum speed of the mob in meters per second.
  165. @export var max_speed = 18
  166. # Emitted when the player jumped on the mob
  167. signal squashed
  168. func _physics_process(_delta):
  169. move_and_slide()
  170. # This function will be called from the Main scene.
  171. func initialize(start_position, player_position):
  172. # We position the mob by placing it at start_position
  173. # and rotate it towards player_position, so it looks at the player.
  174. look_at_from_position(start_position, player_position, Vector3.UP)
  175. # Rotate this mob randomly within range of -90 and +90 degrees,
  176. # so that it doesn't move directly towards the player.
  177. rotate_y(randf_range(-PI / 4, PI / 4))
  178. # We calculate a random speed (integer)
  179. var random_speed = randi_range(min_speed, max_speed)
  180. # We calculate a forward velocity that represents the speed.
  181. velocity = Vector3.FORWARD * random_speed
  182. # We then rotate the velocity vector based on the mob's Y rotation
  183. # in order to move in the direction the mob is looking.
  184. velocity = velocity.rotated(Vector3.UP, rotation.y)
  185. func _on_visible_on_screen_notifier_3d_screen_exited():
  186. queue_free()
  187. func squash():
  188. squashed.emit()
  189. queue_free() # Destroy this node
  190. .. code-tab:: csharp
  191. using Godot;
  192. public partial class Mob : CharacterBody3D
  193. {
  194. // Emitted when the played jumped on the mob.
  195. [Signal]
  196. public delegate void SquashedEventHandler();
  197. // Minimum speed of the mob in meters per second
  198. [Export]
  199. public int MinSpeed { get; set; } = 10;
  200. // Maximum speed of the mob in meters per second
  201. [Export]
  202. public int MaxSpeed { get; set; } = 18;
  203. public override void _PhysicsProcess(double delta)
  204. {
  205. MoveAndSlide();
  206. }
  207. // This function will be called from the Main scene.
  208. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  209. {
  210. // We position the mob by placing it at startPosition
  211. // and rotate it towards playerPosition, so it looks at the player.
  212. LookAtFromPosition(startPosition, playerPosition, Vector3.Up);
  213. // Rotate this mob randomly within range of -90 and +90 degrees,
  214. // so that it doesn't move directly towards the player.
  215. RotateY((float)GD.RandRange(-Mathf.Pi / 4.0, Mathf.Pi / 4.0));
  216. // We calculate a random speed (integer)
  217. int randomSpeed = GD.RandRange(MinSpeed, MaxSpeed);
  218. // We calculate a forward velocity that represents the speed.
  219. Velocity = Vector3.Forward * randomSpeed;
  220. // We then rotate the velocity vector based on the mob's Y rotation
  221. // in order to move in the direction the mob is looking.
  222. Velocity = Velocity.Rotated(Vector3.Up, Rotation.Y);
  223. }
  224. public void Squash()
  225. {
  226. EmitSignal(SignalName.Squashed);
  227. QueueFree(); // Destroy this node
  228. }
  229. private void OnVisibilityNotifierScreenExited()
  230. {
  231. QueueFree();
  232. }
  233. }
  234. Finally, the longest script, ``Player.gd``:
  235. .. tabs::
  236. .. code-tab:: gdscript GDScript
  237. extends CharacterBody3D
  238. signal hit
  239. # How fast the player moves in meters per second
  240. @export var speed = 14
  241. # The downward acceleration while in the air, in meters per second squared.
  242. @export var fall_acceleration = 75
  243. # Vertical impulse applied to the character upon jumping in meters per second.
  244. @export var jump_impulse = 20
  245. # Vertical impulse applied to the character upon bouncing over a mob
  246. # in meters per second.
  247. @export var bounce_impulse = 16
  248. var target_velocity = Vector3.ZERO
  249. func _physics_process(delta):
  250. # We create a local variable to store the input direction
  251. var direction = Vector3.ZERO
  252. # We check for each move input and update the direction accordingly
  253. if Input.is_action_pressed("move_right"):
  254. direction.x = direction.x + 1
  255. if Input.is_action_pressed("move_left"):
  256. direction.x = direction.x - 1
  257. if Input.is_action_pressed("move_back"):
  258. # Notice how we are working with the vector's x and z axes.
  259. # In 3D, the XZ plane is the ground plane.
  260. direction.z = direction.z + 1
  261. if Input.is_action_pressed("move_forward"):
  262. direction.z = direction.z - 1
  263. # Prevent diagonal moving fast af
  264. if direction != Vector3.ZERO:
  265. direction = direction.normalized()
  266. $Pivot.look_at(position + direction, Vector3.UP)
  267. # Ground Velocity
  268. target_velocity.x = direction.x * speed
  269. target_velocity.z = direction.z * speed
  270. # Vertical Velocity
  271. if not is_on_floor(): # If in the air, fall towards the floor. Literally gravity
  272. target_velocity.y = target_velocity.y - (fall_acceleration * delta)
  273. # Jumping.
  274. if is_on_floor() and Input.is_action_just_pressed("jump"):
  275. target_velocity.y = jump_impulse
  276. # Iterate through all collisions that occurred this frame
  277. # in C this would be for(int i = 0; i < collisions.Count; i++)
  278. for index in range(get_slide_collision_count()):
  279. # We get one of the collisions with the player
  280. var collision = get_slide_collision(index)
  281. # If the collision is with ground
  282. if collision.get_collider() == null:
  283. continue
  284. # If the collider is with a mob
  285. if collision.get_collider().is_in_group("mob"):
  286. var mob = collision.get_collider()
  287. # we check that we are hitting it from above.
  288. if Vector3.UP.dot(collision.get_normal()) > 0.1:
  289. # If so, we squash it and bounce.
  290. mob.squash()
  291. target_velocity.y = bounce_impulse
  292. # Prevent further duplicate calls.
  293. break
  294. # Moving the Character
  295. velocity = target_velocity
  296. move_and_slide()
  297. # And this function at the bottom.
  298. func die():
  299. hit.emit()
  300. queue_free()
  301. func _on_mob_detector_body_entered(body):
  302. die()
  303. .. code-tab:: csharp
  304. using Godot;
  305. public partial class Player : CharacterBody3D
  306. {
  307. // Emitted when the player was hit by a mob.
  308. [Signal]
  309. public delegate void HitEventHandler();
  310. // How fast the player moves in meters per second.
  311. [Export]
  312. public int Speed { get; set; } = 14;
  313. // The downward acceleration when in the air, in meters per second squared.
  314. [Export]
  315. public int FallAcceleration { get; set; } = 75;
  316. // Vertical impulse applied to the character upon jumping in meters per second.
  317. [Export]
  318. public int JumpImpulse { get; set; } = 20;
  319. // Vertical impulse applied to the character upon bouncing over a mob in meters per second.
  320. [Export]
  321. public int BounceImpulse { get; set; } = 16;
  322. private Vector3 _targetVelocity = Vector3.Zero;
  323. public override void _PhysicsProcess(double delta)
  324. {
  325. // We create a local variable to store the input direction.
  326. var direction = Vector3.Zero;
  327. // We check for each move input and update the direction accordingly.
  328. if (Input.IsActionPressed("move_right"))
  329. {
  330. direction.X += 1.0f;
  331. }
  332. if (Input.IsActionPressed("move_left"))
  333. {
  334. direction.X -= 1.0f;
  335. }
  336. if (Input.IsActionPressed("move_back"))
  337. {
  338. // Notice how we are working with the vector's X and Z axes.
  339. // In 3D, the XZ plane is the ground plane.
  340. direction.Z += 1.0f;
  341. }
  342. if (Input.IsActionPressed("move_forward"))
  343. {
  344. direction.Z -= 1.0f;
  345. }
  346. // Prevent diagonal moving fast af
  347. if (direction != Vector3.Zero)
  348. {
  349. direction = direction.Normalized();
  350. GetNode<Node3D>("Pivot").LookAt(Position + direction, Vector3.Up);
  351. }
  352. // Ground Velocity
  353. _targetVelocity.X = direction.X * Speed;
  354. _targetVelocity.Z = direction.Z * Speed;
  355. // Vertical Velocity
  356. if (!IsOnFloor()) // If in the air, fall towards the floor. Literally gravity
  357. {
  358. _targetVelocity.Y -= FallAcceleration * (float)delta;
  359. }
  360. // Jumping.
  361. if (IsOnFloor() && Input.IsActionJustPressed("jump"))
  362. {
  363. _targetVelocity.Y = JumpImpulse;
  364. }
  365. // Iterate through all collisions that occurred this frame.
  366. for (int index = 0; index < GetSlideCollisionCount(); index++)
  367. {
  368. // We get one of the collisions with the player.
  369. KinematicCollision3D collision = GetSlideCollision(index);
  370. // If the collision is with a mob.
  371. if (collision.GetCollider() is Mob mob)
  372. {
  373. // We check that we are hitting it from above.
  374. if (Vector3.Up.Dot(collision.GetNormal()) > 0.1f)
  375. {
  376. // If so, we squash it and bounce.
  377. mob.Squash();
  378. _targetVelocity.Y = BounceImpulse;
  379. // Prevent further duplicate calls.
  380. break;
  381. }
  382. }
  383. }
  384. // Moving the Character
  385. Velocity = _targetVelocity;
  386. MoveAndSlide();
  387. }
  388. private void Die()
  389. {
  390. EmitSignal(SignalName.Hit);
  391. QueueFree();
  392. }
  393. private void OnMobDetectorBodyEntered(Node3D body)
  394. {
  395. Die();
  396. }
  397. }
  398. See you in the next lesson to add the score and the retry option.
  399. .. |image0| image:: img/07.killing_player/01.adding_area_node.png
  400. .. |image1| image:: img/07.killing_player/02.cylinder_shape.png
  401. .. |image2| image:: img/07.killing_player/03.cylinder_in_editor.png
  402. .. |image3| image:: img/07.killing_player/04.mob_detector_properties.webp
  403. .. |image4| image:: img/07.killing_player/05.body_entered_signal.png
  404. .. |image5| image:: img/07.killing_player/06.player_hit_signal.png