03.player_movement_code.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. :article_outdated: True
  2. .. _doc_first_3d_game_player_movement:
  3. Moving the player with code
  4. ===========================
  5. It's time to code! We're going to use the input actions we created in the last
  6. part to move the character.
  7. Right-click the ``Player`` node and select *Attach Script* to add a new script to
  8. it. In the popup, set the *Template* to *Empty* before pressing the *Create*
  9. button.
  10. |image0|
  11. Let's start with the class's properties. We're going to define a movement speed,
  12. a fall acceleration representing gravity, and a velocity we'll use to move the
  13. character.
  14. .. tabs::
  15. .. code-tab:: gdscript GDScript
  16. extends CharacterBody3D
  17. # How fast the player moves in meters per second.
  18. @export var speed = 14
  19. # The downward acceleration when in the air, in meters per second squared.
  20. @export var fall_acceleration = 75
  21. var target_velocity = Vector3.ZERO
  22. .. code-tab:: csharp
  23. using Godot;
  24. public partial class Player : CharacterBody3D
  25. {
  26. // Don't forget to rebuild the project so the editor knows about the new export variable.
  27. // How fast the player moves in meters per second.
  28. [Export]
  29. public int Speed { get; set; } = 14;
  30. // The downward acceleration when in the air, in meters per second squared.
  31. [Export]
  32. public int FallAcceleration { get; set; } = 75;
  33. private Vector3 _targetVelocity = Vector3.Zero;
  34. }
  35. These are common properties for a moving body. The ``target_velocity`` is a :ref:`3D vector <class_Vector3>`
  36. combining a speed with a direction. Here, we define it as a property because
  37. we want to update and reuse its value across frames.
  38. .. note::
  39. The values are quite different from 2D code because distances are in meters.
  40. While in 2D, a thousand units (pixels) may only correspond to half of your
  41. screen's width, in 3D, it's a kilometer.
  42. Let's code the movement. We start by calculating the input direction vector
  43. using the global ``Input`` object, in ``_physics_process()``.
  44. .. tabs::
  45. .. code-tab:: gdscript GDScript
  46. func _physics_process(delta):
  47. # We create a local variable to store the input direction.
  48. var direction = Vector3.ZERO
  49. # We check for each move input and update the direction accordingly.
  50. if Input.is_action_pressed("move_right"):
  51. direction.x += 1
  52. if Input.is_action_pressed("move_left"):
  53. direction.x -= 1
  54. if Input.is_action_pressed("move_back"):
  55. # Notice how we are working with the vector's x and z axes.
  56. # In 3D, the XZ plane is the ground plane.
  57. direction.z += 1
  58. if Input.is_action_pressed("move_forward"):
  59. direction.z -= 1
  60. .. code-tab:: csharp
  61. public override void _PhysicsProcess(double delta)
  62. {
  63. // We create a local variable to store the input direction.
  64. var direction = Vector3.Zero;
  65. // We check for each move input and update the direction accordingly.
  66. if (Input.IsActionPressed("move_right"))
  67. {
  68. direction.X += 1.0f;
  69. }
  70. if (Input.IsActionPressed("move_left"))
  71. {
  72. direction.X -= 1.0f;
  73. }
  74. if (Input.IsActionPressed("move_back"))
  75. {
  76. // Notice how we are working with the vector's X and Z axes.
  77. // In 3D, the XZ plane is the ground plane.
  78. direction.Z += 1.0f;
  79. }
  80. if (Input.IsActionPressed("move_forward"))
  81. {
  82. direction.Z -= 1.0f;
  83. }
  84. }
  85. Here, we're going to make all calculations using the ``_physics_process()``
  86. virtual function. Like ``_process()``, it allows you to update the node every
  87. frame, but it's designed specifically for physics-related code like moving a
  88. kinematic or rigid body.
  89. .. seealso::
  90. To learn more about the difference between ``_process()`` and
  91. ``_physics_process()``, see :ref:`doc_idle_and_physics_processing`.
  92. We start by initializing a ``direction`` variable to ``Vector3.ZERO``. Then, we
  93. check if the player is pressing one or more of the ``move_*`` inputs and update
  94. the vector's ``x`` and ``z`` components accordingly. These correspond to the
  95. ground plane's axes.
  96. These four conditions give us eight possibilities and eight possible directions.
  97. In case the player presses, say, both W and D simultaneously, the vector will
  98. have a length of about ``1.4``. But if they press a single key, it will have a
  99. length of ``1``. We want the vector's length to be consistent, and not move faster diagonally. To do so, we can
  100. call its ``normalize()`` method.
  101. .. tabs::
  102. .. code-tab:: gdscript GDScript
  103. #func _physics_process(delta):
  104. #...
  105. if direction != Vector3.ZERO:
  106. direction = direction.normalized()
  107. $Pivot.look_at(position + direction, Vector3.UP)
  108. .. code-tab:: csharp
  109. public override void _PhysicsProcess(double delta)
  110. {
  111. // ...
  112. if (direction != Vector3.Zero)
  113. {
  114. direction = direction.Normalized();
  115. GetNode<Node3D>("Pivot").LookAt(Position + direction, Vector3.Up);
  116. }
  117. }
  118. Here, we only normalize the vector if the direction has a length greater than
  119. zero, which means the player is pressing a direction key.
  120. In this case, we also get the ``Pivot`` node and call its ``look_at()`` method.
  121. This method takes a position in space to look at in global coordinates and the
  122. up direction. In this case, we can use the ``Vector3.UP`` constant.
  123. .. note::
  124. A node's local coordinates, like ``position``, are relative to their
  125. parent. Global coordinates, like ``global_position`` are relative to the world's main axes you can see
  126. in the viewport instead.
  127. In 3D, the property that contains a node's position is ``position``. By
  128. adding the ``direction`` to it, we get a position to look at that's one meter
  129. away from the ``Player``.
  130. Then, we update the velocity. We have to calculate the ground velocity and the
  131. fall speed separately. Be sure to go back one tab so the lines are inside the
  132. ``_physics_process()`` function but outside the condition we just wrote above.
  133. .. tabs::
  134. .. code-tab:: gdscript GDScript
  135. func _physics_process(delta):
  136. #...
  137. if direction != Vector3.ZERO:
  138. #...
  139. # Ground Velocity
  140. target_velocity.x = direction.x * speed
  141. target_velocity.z = direction.z * speed
  142. # Vertical Velocity
  143. if not is_on_floor(): # If in the air, fall towards the floor. Literally gravity
  144. target_velocity.y = target_velocity.y - (fall_acceleration * delta)
  145. # Moving the Character
  146. velocity = target_velocity
  147. move_and_slide()
  148. .. code-tab:: csharp
  149. public override void _PhysicsProcess(double delta)
  150. {
  151. // ...
  152. if (direction != Vector3.Zero)
  153. {
  154. // ...
  155. }
  156. // Ground velocity
  157. _targetVelocity.X = direction.X * Speed;
  158. _targetVelocity.Z = direction.Z * Speed;
  159. // Vertical velocity
  160. if (!IsOnFloor()) // If in the air, fall towards the floor. Literally gravity
  161. {
  162. _targetVelocity.Y -= FallAcceleration * (float)delta;
  163. }
  164. // Moving the character
  165. Velocity = _targetVelocity;
  166. MoveAndSlide();
  167. }
  168. The ``CharacterBody3D.is_on_floor()`` function returns ``true`` if the body collided with the floor in this frame. That's why
  169. we apply gravity to the ``Player`` only while it is in the air.
  170. For the vertical velocity, we subtract the fall acceleration multiplied by the
  171. delta time every frame.
  172. This line of code will cause our character to fall in every frame, as long it is not on or collides with the floor.
  173. The physics engine can only detect interactions with walls, the floor, or other
  174. bodies during a given frame if movement and collisions happen. We will use this
  175. property later to code the jump.
  176. On the last line, we call ``CharacterBody3D.move_and_slide()`` which is a powerful
  177. method of the ``CharacterBody3D`` class that allows you to move a character
  178. smoothly. If it hits a wall midway through a motion, the engine will try to
  179. smooth it out for you. It uses the *velocity* value native to the :ref:`CharacterBody3D <class_CharacterBody3D>`
  180. .. OLD TEXT: The function takes two parameters: our velocity and the up direction. It moves
  181. .. the character and returns a leftover velocity after applying collisions. When
  182. .. hitting the floor or a wall, the function will reduce or reset the speed in that
  183. .. direction from you. In our case, storing the function's returned value prevents
  184. .. the character from accumulating vertical momentum, which could otherwise get so
  185. .. big the character would move through the ground slab after a while.
  186. And that's all the code you need to move the character on the floor.
  187. Here is the complete ``Player.gd`` code for reference.
  188. .. tabs::
  189. .. code-tab:: gdscript GDScript
  190. extends CharacterBody3D
  191. # How fast the player moves in meters per second.
  192. @export var speed = 14
  193. # The downward acceleration when in the air, in meters per second squared.
  194. @export var fall_acceleration = 75
  195. var target_velocity = Vector3.ZERO
  196. func _physics_process(delta):
  197. var direction = Vector3.ZERO
  198. if Input.is_action_pressed("move_right"):
  199. direction.x += 1
  200. if Input.is_action_pressed("move_left"):
  201. direction.x -= 1
  202. if Input.is_action_pressed("move_back"):
  203. direction.z += 1
  204. if Input.is_action_pressed("move_forward"):
  205. direction.z -= 1
  206. if direction != Vector3.ZERO:
  207. direction = direction.normalized()
  208. $Pivot.look_at(position + direction, Vector3.UP)
  209. # Ground Velocity
  210. target_velocity.x = direction.x * speed
  211. target_velocity.z = direction.z * speed
  212. # Vertical Velocity
  213. if not is_on_floor(): # If in the air, fall towards the floor. Literally gravity
  214. target_velocity.y = target_velocity.y - (fall_acceleration * delta)
  215. # Moving the Character
  216. velocity = target_velocity
  217. move_and_slide()
  218. .. code-tab:: csharp
  219. using Godot;
  220. public partial class Player : CharacterBody3D
  221. {
  222. // How fast the player moves in meters per second.
  223. [Export]
  224. public int Speed { get; set; } = 14;
  225. // The downward acceleration when in the air, in meters per second squared.
  226. [Export]
  227. public int FallAcceleration { get; set; } = 75;
  228. private Vector3 _targetVelocity = Vector3.Zero;
  229. public override void _PhysicsProcess(double delta)
  230. {
  231. var direction = Vector3.Zero;
  232. if (Input.IsActionPressed("move_right"))
  233. {
  234. direction.X += 1.0f;
  235. }
  236. if (Input.IsActionPressed("move_left"))
  237. {
  238. direction.X -= 1.0f;
  239. }
  240. if (Input.IsActionPressed("move_back"))
  241. {
  242. direction.Z += 1.0f;
  243. }
  244. if (Input.IsActionPressed("move_forward"))
  245. {
  246. direction.Z -= 1.0f;
  247. }
  248. if (direction != Vector3.Zero)
  249. {
  250. direction = direction.Normalized();
  251. GetNode<Node3D>("Pivot").LookAt(Position + direction, Vector3.Up);
  252. }
  253. // Ground velocity
  254. _targetVelocity.X = direction.X * Speed;
  255. _targetVelocity.Z = direction.Z * Speed;
  256. // Vertical velocity
  257. if (!IsOnFloor()) // If in the air, fall towards the floor. Literally gravity
  258. {
  259. _targetVelocity.Y -= FallAcceleration * (float)delta;
  260. }
  261. // Moving the character
  262. Velocity = _targetVelocity;
  263. MoveAndSlide();
  264. }
  265. }
  266. Testing our player's movement
  267. -----------------------------
  268. We're going to put our player in the ``Main`` scene to test it. To do so, we need
  269. to instantiate the player and then add a camera. Unlike in 2D, in 3D, you won't
  270. see anything if your viewport doesn't have a camera pointing at something.
  271. Save your ``Player`` scene and open the ``Main`` scene. You can click on the *Main*
  272. tab at the top of the editor to do so.
  273. |image1|
  274. If you closed the scene before, head to the *FileSystem* dock and double-click
  275. ``main.tscn`` to re-open it.
  276. To instantiate the ``Player``, right-click on the ``Main`` node and select *Instance
  277. Child Scene*.
  278. |image2|
  279. In the popup, double-click ``player.tscn``. The character should appear in the
  280. center of the viewport.
  281. Adding a camera
  282. ~~~~~~~~~~~~~~~
  283. Let's add the camera next. Like we did with our *Player*\ 's *Pivot*, we're
  284. going to create a basic rig. Right-click on the ``Main`` node again and select
  285. *Add Child Node*. Create a new :ref:`Marker3D <class_Marker3D>`, and name it ``CameraPivot``. Select ``CameraPivot`` and add a child node :ref:`Camera3D <class_Camera3D>` to it. Your scene tree should look like this.
  286. |image3|
  287. Notice the *Preview* checkbox that appears in the top-left when you have the
  288. *Camera* selected. You can click it to preview the in-game camera projection.
  289. |image4|
  290. We're going to use the *Pivot* to rotate the camera as if it was on a crane.
  291. Let's first split the 3D view to be able to freely navigate the scene and see
  292. what the camera sees.
  293. In the toolbar right above the viewport, click on *View*, then *2 Viewports*.
  294. You can also press :kbd:`Ctrl + 2` (:kbd:`Cmd + 2` on macOS).
  295. |image11|
  296. |image5|
  297. On the bottom view, select your :ref:`Camera3D <class_Camera3D>` and turn on camera Preview by clicking
  298. the checkbox.
  299. |image6|
  300. In the top view, move the camera about ``19`` units on the Z axis (the blue
  301. one).
  302. |image7|
  303. Here's where the magic happens. Select the *CameraPivot* and rotate it ``-45``
  304. degrees around the X axis (using the red circle). You'll see the camera move as
  305. if it was attached to a crane.
  306. |image8|
  307. You can run the scene by pressing :kbd:`F6` and press the arrow keys to move the
  308. character.
  309. |image9|
  310. We can see some empty space around the character due to the perspective
  311. projection. In this game, we're going to use an orthographic projection instead
  312. to better frame the gameplay area and make it easier for the player to read
  313. distances.
  314. Select the *Camera* again and in the *Inspector*, set the *Projection* to
  315. *Orthogonal* and the *Size* to ``19``. The character should now look flatter and
  316. the ground should fill the background.
  317. .. note::
  318. When using an orthogonal camera in Godot 4, directional shadow quality is
  319. dependent on the camera's *Far* value. The higher the *Far* value, the
  320. further away the camera will be able to see. However, higher *Far* values
  321. also decrease shadow quality as the shadow rendering has to cover a greater
  322. distance.
  323. If directional shadows look too blurry after switching to an orthogonal
  324. camera, decrease the camera's *Far* property to a lower value such as
  325. ``100``. Don't decrease this *Far* property too much, or objects in the
  326. distance will start disappearing.
  327. |image10|
  328. Test your scene and you should be able to move in all 8 directions and not glitch through the floor!
  329. Ultimately, we have both player movement and the view in place. Next, we will
  330. work on the monsters.
  331. .. |image0| image:: img/03.player_movement_code/01.attach_script_to_player.webp
  332. .. |image1| image:: img/03.player_movement_code/02.clicking_main_tab.png
  333. .. |image2| image:: img/03.player_movement_code/03.instance_child_scene.png
  334. .. |image3| image:: img/03.player_movement_code/04.scene_tree_with_camera.png
  335. .. |image4| image:: img/03.player_movement_code/05.camera_preview_checkbox.png
  336. .. |image5| image:: img/03.player_movement_code/06.two_viewports.png
  337. .. |image6| image:: img/03.player_movement_code/07.camera_preview_checkbox.png
  338. .. |image7| image:: img/03.player_movement_code/08.camera_moved.png
  339. .. |image8| image:: img/03.player_movement_code/09.camera_rotated.png
  340. .. |image9| image:: img/03.player_movement_code/10.camera_perspective.png
  341. .. |image10| image:: img/03.player_movement_code/13.camera3d_values.webp
  342. .. |image11| image:: img/03.player_movement_code/12.viewport_change.webp