03.player_movement_code.rst 16 KB

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