03.player_movement_code.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. .. _doc_first_3d_game_player_movement:
  2. Moving the player with code
  3. ===========================
  4. It's time to code! We're going to use the input actions we created in the last
  5. part to move the character.
  6. Right-click the *Player* node and select *Attach Script* to add a new script to
  7. it. In the popup, set the *Template* to *Empty* before pressing the *Create*
  8. button.
  9. |image0|
  10. Let's start with the class's properties. We're going to define a movement speed,
  11. a fall acceleration representing gravity, and a velocity we'll use to move the
  12. character.
  13. ::
  14. extends KinematicBody
  15. # How fast the player moves in meters per second.
  16. export var speed = 14
  17. # The downward acceleration when in the air, in meters per second squared.
  18. export var fall_acceleration = 75
  19. var velocity = Vector3.ZERO
  20. These are common properties for a moving body. The ``velocity`` is a 3D vector
  21. combining a speed with a direction. Here, we define it as a property because
  22. we want to update and reuse its value across frames.
  23. .. note::
  24. The values are quite different from 2D code because distances are in meters.
  25. While in 2D, a thousand units (pixels) may only correspond to half of your
  26. screen's width, in 3D, it's a kilometer.
  27. Let's code the movement now. We start by calculating the input direction vector
  28. using the global ``Input`` object, in ``_physics_process()``.
  29. ::
  30. func _physics_process(delta):
  31. # We create a local variable to store the input direction.
  32. var direction = Vector3.ZERO
  33. # We check for each move input and update the direction accordingly.
  34. if Input.is_action_pressed("move_right"):
  35. direction.x += 1
  36. if Input.is_action_pressed("move_left"):
  37. direction.x -= 1
  38. if Input.is_action_pressed("move_back"):
  39. # Notice how we are working with the vector's x and z axes.
  40. # In 3D, the XZ plane is the ground plane.
  41. direction.z += 1
  42. if Input.is_action_pressed("move_forward"):
  43. direction.z -= 1
  44. Here, we're going to make all calculations using the ``_physics_process()``
  45. virtual function. Like ``_process()``, it allows you to update the node every
  46. frame, but it's designed specifically for physics-related code like moving a
  47. kinematic or rigid body.
  48. .. seealso::
  49. To learn more about the difference between ``_process()`` and
  50. ``_physics_process()``, see :ref:`doc_idle_and_physics_processing`.
  51. We start by initializing a ``direction`` variable to ``Vector3.ZERO``. Then, we
  52. check if the player is pressing one or more of the ``move_*`` inputs and update
  53. the vector's ``x`` and ``z`` components accordingly. These correspond to the
  54. ground plane's axes.
  55. These four conditions give us eight possibilities and eight possible directions.
  56. In case the player presses, say, both W and D simultaneously, the vector will
  57. have a length of about ``1.4``. But if they press a single key, it will have a
  58. length of ``1``. We want the vector's length to be consistent. To do so, we can
  59. call its ``normalize()`` method.
  60. ::
  61. #func _physics_process(delta):
  62. #...
  63. if direction != Vector3.ZERO:
  64. direction = direction.normalized()
  65. $Pivot.look_at(translation + direction, Vector3.UP)
  66. Here, we only normalize the vector if the direction has a length greater than
  67. zero, which means the player is pressing a direction key.
  68. In this case, we also get the *Pivot* node and call its ``look_at()`` method.
  69. This method takes a position in space to look at in global coordinates and the
  70. up direction. In this case, we can use the ``Vector3.UP`` constant.
  71. .. note::
  72. A node's local coordinates, like ``translation``, are relative to their
  73. parent. Global coordinates are relative to the world's main axes you can see
  74. in the viewport instead.
  75. In 3D, the property that contains a node's position is ``translation``. By
  76. adding the ``direction`` to it, we get a position to look at that's one meter
  77. away from the *Player*.
  78. Then, we update the velocity. We have to calculate the ground velocity and the
  79. fall speed separately. Be sure to go back one tab so the lines are inside the
  80. ``_physics_process()`` function but outside the condition we just wrote.
  81. ::
  82. func _physics_process(delta):_
  83. #...
  84. if direction != Vector3.ZERO:
  85. #...
  86. # Ground velocity
  87. velocity.x = direction.x * speed
  88. velocity.z = direction.z * speed
  89. # Vertical velocity
  90. velocity.y -= fall_acceleration * delta
  91. # Moving the character
  92. velocity = move_and_slide(velocity, Vector3.UP)
  93. For the vertical velocity, we subtract the fall acceleration multiplied by the
  94. delta time every frame. Notice the use of the ``-=`` operator, which is a
  95. shorthand for ``variable = variable - ...``.
  96. This line of code will cause our character to fall in every frame. This may seem
  97. strange if it's already on the floor. But we have to do this for the character
  98. to collide with the ground every frame.
  99. The physics engine can only detect interactions with walls, the floor, or other
  100. bodies during a given frame if movement and collisions happen. We will use this
  101. property later to code the jump.
  102. On the last line, we call ``KinematicBody.move_and_slide()``. It's a powerful
  103. method of the ``KinematicBody`` class that allows you to move a character
  104. smoothly. If it hits a wall midway through a motion, the engine will try to
  105. smooth it out for you.
  106. The function takes two parameters: our velocity and the up direction. It moves
  107. the character and returns a leftover velocity after applying collisions. When
  108. hitting the floor or a wall, the function will reduce or reset the speed in that
  109. direction from you. In our case, storing the function's returned value prevents
  110. the character from accumulating vertical momentum, which could otherwise get so
  111. big the character would move through the ground slab after a while.
  112. And that's all the code you need to move the character on the floor.
  113. Here is the complete ``Player.gd`` code for reference.
  114. ::
  115. extends KinematicBody
  116. # How fast the player moves in meters per second.
  117. export var speed = 14
  118. # The downward acceleration when in the air, in meters per second squared.
  119. export var fall_acceleration = 75
  120. var velocity = Vector3.ZERO
  121. func _physics_process(delta):
  122. var direction = Vector3.ZERO
  123. if Input.is_action_pressed("move_right"):
  124. direction.x += 1
  125. if Input.is_action_pressed("move_left"):
  126. direction.x -= 1
  127. if Input.is_action_pressed("move_back"):
  128. direction.z += 1
  129. if Input.is_action_pressed("move_forward"):
  130. direction.z -= 1
  131. if direction != Vector3.ZERO:
  132. direction = direction.normalized()
  133. $Pivot.look_at(translation + direction, Vector3.UP)
  134. velocity.x = direction.x * speed
  135. velocity.z = direction.z * speed
  136. velocity.y -= fall_acceleration * delta
  137. velocity = move_and_slide(velocity, Vector3.UP)
  138. Testing our player's movement
  139. -----------------------------
  140. We're going to put our player in the *Main* scene to test it. To do so, we need
  141. to instantiate the player and then add a camera. Unlike in 2D, in 3D, you won't
  142. see anything if your viewport doesn't have a camera pointing at something.
  143. Save your *Player* scene and open the *Main* scene. You can click on the *Main*
  144. tab at the top of the editor to do so.
  145. |image1|
  146. If you closed the scene before, head to the *FileSystem* dock and double-click
  147. ``Main.tscn`` to re-open it.
  148. To instantiate the *Player*, right-click on the *Main* node and select *Instance
  149. Child Scene*.
  150. |image2|
  151. In the popup, double-click *Player.tscn*. The character should appear in the
  152. center of the viewport.
  153. Adding a camera
  154. ~~~~~~~~~~~~~~~
  155. Let's add the camera next. Like we did with our *Player*\ 's *Pivot*, we're
  156. going to create a basic rig. Right-click on the *Main* node again and select
  157. *Add Child Node* this time. Create a new *Position3D*, name it *CameraPivot*,
  158. and add a *Camera* node as a child of it. Your scene tree should look like this.
  159. |image3|
  160. Notice the *Preview* checkbox that appears in the top-left when you have the
  161. *Camera* selected. You can click it to preview the in-game camera projection.
  162. |image4|
  163. We're going to use the *Pivot* to rotate the camera as if it was on a crane.
  164. Let's first split the 3D view to be able to freely navigate the scene and see
  165. what the camera sees.
  166. In the toolbar right above the viewport, click on *View*, then *2 Viewports*.
  167. You can also press :kbd:`Ctrl + 2` (:kbd:`Cmd + 2` on MacOS).
  168. |image5|
  169. On the bottom view, select the *Camera* and turn on camera preview by clicking
  170. the checkbox.
  171. |image6|
  172. In the top view, move the camera about ``19`` units on the Z axis (the blue
  173. one).
  174. |image7|
  175. Here's where the magic happens. Select the *CameraPivot* and rotate it ``45``
  176. degrees around the X axis (using the red circle). You'll see the camera move as
  177. if it was attached to a crane.
  178. |image8|
  179. You can run the scene by pressing :kbd:`F6` and press the arrow keys to move the
  180. character.
  181. |image9|
  182. We can see some empty space around the character due to the perspective
  183. projection. In this game, we're going to use an orthographic projection instead
  184. to better frame the gameplay area and make it easier for the player to read
  185. distances.
  186. Select the *Camera* again and in the *Inspector*, set the *Projection* to
  187. *Orthogonal* and the *Size* to ``19``. The character should now look flatter and
  188. the ground should fill the background.
  189. |image10|
  190. With that, we have both player movement and the view in place. Next, we will
  191. work on the monsters.
  192. .. |image0| image:: img/03.player_movement_code/01.attach_script_to_player.png
  193. .. |image1| image:: img/03.player_movement_code/02.clicking_main_tab.png
  194. .. |image2| image:: img/03.player_movement_code/03.instance_child_scene.png
  195. .. |image3| image:: img/03.player_movement_code/04.scene_tree_with_camera.png
  196. .. |image4| image:: img/03.player_movement_code/05.camera_preview_checkbox.png
  197. .. |image5| image:: img/03.player_movement_code/06.two_viewports.png
  198. .. |image6| image:: img/03.player_movement_code/07.camera_preview_checkbox.png
  199. .. |image7| image:: img/03.player_movement_code/08.camera_moved.png
  200. .. |image8| image:: img/03.player_movement_code/09.camera_rotated.png
  201. .. |image9| image:: img/03.player_movement_code/10.camera_perspective.png
  202. .. |image10| image:: img/03.player_movement_code/11.camera_orthographic.png