03.player_movement_code.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 ``normalized()`` method.
  101. .. tabs::
  102. .. code-tab:: gdscript GDScript
  103. #func _physics_process(delta):
  104. #...
  105. if direction != Vector3.ZERO:
  106. direction = direction.normalized()
  107. # Setting the basis property will affect the rotation of the node.
  108. $Pivot.basis = Basis.looking_at(direction)
  109. .. code-tab:: csharp
  110. public override void _PhysicsProcess(double delta)
  111. {
  112. // ...
  113. if (direction != Vector3.Zero)
  114. {
  115. direction = direction.Normalized();
  116. // Setting the basis property will affect the rotation of the node.
  117. GetNode<Node3D>("Pivot").Basis = Basis.LookingAt(direction);
  118. }
  119. }
  120. Here, we only normalize the vector if the direction has a length greater than
  121. zero, which means the player is pressing a direction key.
  122. We compute the direction the ``$Pivot`` is looking by creating a :ref:`Basis <class_Basis>`
  123. that looks in the ``direction`` direction.
  124. Then, we update the velocity. We have to calculate the ground velocity and the
  125. fall speed separately. Be sure to go back one tab so the lines are inside the
  126. ``_physics_process()`` function but outside the condition we just wrote above.
  127. .. tabs::
  128. .. code-tab:: gdscript GDScript
  129. func _physics_process(delta):
  130. #...
  131. if direction != Vector3.ZERO:
  132. #...
  133. # Ground Velocity
  134. target_velocity.x = direction.x * speed
  135. target_velocity.z = direction.z * speed
  136. # Vertical Velocity
  137. if not is_on_floor(): # If in the air, fall towards the floor. Literally gravity
  138. target_velocity.y = target_velocity.y - (fall_acceleration * delta)
  139. # Moving the Character
  140. velocity = target_velocity
  141. move_and_slide()
  142. .. code-tab:: csharp
  143. public override void _PhysicsProcess(double delta)
  144. {
  145. // ...
  146. if (direction != Vector3.Zero)
  147. {
  148. // ...
  149. }
  150. // Ground velocity
  151. _targetVelocity.X = direction.X * Speed;
  152. _targetVelocity.Z = direction.Z * Speed;
  153. // Vertical velocity
  154. if (!IsOnFloor()) // If in the air, fall towards the floor. Literally gravity
  155. {
  156. _targetVelocity.Y -= FallAcceleration * (float)delta;
  157. }
  158. // Moving the character
  159. Velocity = _targetVelocity;
  160. MoveAndSlide();
  161. }
  162. The ``CharacterBody3D.is_on_floor()`` function returns ``true`` if the body collided with the floor in this frame. That's why
  163. we apply gravity to the ``Player`` only while it is in the air.
  164. For the vertical velocity, we subtract the fall acceleration multiplied by the
  165. delta time every frame.
  166. This line of code will cause our character to fall in every frame, as long as it is not on or colliding with the floor.
  167. The physics engine can only detect interactions with walls, the floor, or other
  168. bodies during a given frame if movement and collisions happen. We will use this
  169. property later to code the jump.
  170. On the last line, we call ``CharacterBody3D.move_and_slide()`` which is a powerful
  171. method of the ``CharacterBody3D`` class that allows you to move a character
  172. smoothly. If it hits a wall midway through a motion, the engine will try to
  173. smooth it out for you. It uses the *velocity* value native to the :ref:`CharacterBody3D <class_CharacterBody3D>`
  174. .. OLD TEXT: The function takes two parameters: our velocity and the up direction. It moves
  175. .. the character and returns a leftover velocity after applying collisions. When
  176. .. hitting the floor or a wall, the function will reduce or reset the speed in that
  177. .. direction from you. In our case, storing the function's returned value prevents
  178. .. the character from accumulating vertical momentum, which could otherwise get so
  179. .. big the character would move through the ground slab after a while.
  180. And that's all the code you need to move the character on the floor.
  181. Here is the complete ``Player.gd`` code for reference.
  182. .. tabs::
  183. .. code-tab:: gdscript GDScript
  184. extends CharacterBody3D
  185. # How fast the player moves in meters per second.
  186. @export var speed = 14
  187. # The downward acceleration when in the air, in meters per second squared.
  188. @export var fall_acceleration = 75
  189. var target_velocity = Vector3.ZERO
  190. func _physics_process(delta):
  191. var direction = Vector3.ZERO
  192. if Input.is_action_pressed("move_right"):
  193. direction.x += 1
  194. if Input.is_action_pressed("move_left"):
  195. direction.x -= 1
  196. if Input.is_action_pressed("move_back"):
  197. direction.z += 1
  198. if Input.is_action_pressed("move_forward"):
  199. direction.z -= 1
  200. if direction != Vector3.ZERO:
  201. direction = direction.normalized()
  202. $Pivot.basis = Basis.looking_at(direction)
  203. # Ground Velocity
  204. target_velocity.x = direction.x * speed
  205. target_velocity.z = direction.z * speed
  206. # Vertical Velocity
  207. if not is_on_floor(): # If in the air, fall towards the floor. Literally gravity
  208. target_velocity.y = target_velocity.y - (fall_acceleration * delta)
  209. # Moving the Character
  210. velocity = target_velocity
  211. move_and_slide()
  212. .. code-tab:: csharp
  213. using Godot;
  214. public partial class Player : CharacterBody3D
  215. {
  216. // How fast the player moves in meters per second.
  217. [Export]
  218. public int Speed { get; set; } = 14;
  219. // The downward acceleration when in the air, in meters per second squared.
  220. [Export]
  221. public int FallAcceleration { get; set; } = 75;
  222. private Vector3 _targetVelocity = Vector3.Zero;
  223. public override void _PhysicsProcess(double delta)
  224. {
  225. var direction = Vector3.Zero;
  226. if (Input.IsActionPressed("move_right"))
  227. {
  228. direction.X += 1.0f;
  229. }
  230. if (Input.IsActionPressed("move_left"))
  231. {
  232. direction.X -= 1.0f;
  233. }
  234. if (Input.IsActionPressed("move_back"))
  235. {
  236. direction.Z += 1.0f;
  237. }
  238. if (Input.IsActionPressed("move_forward"))
  239. {
  240. direction.Z -= 1.0f;
  241. }
  242. if (direction != Vector3.Zero)
  243. {
  244. direction = direction.Normalized();
  245. GetNode<Node3D>("Pivot").Basis = Basis.LookingAt(direction);
  246. }
  247. // Ground velocity
  248. _targetVelocity.X = direction.X * Speed;
  249. _targetVelocity.Z = direction.Z * Speed;
  250. // Vertical velocity
  251. if (!IsOnFloor()) // If in the air, fall towards the floor. Literally gravity
  252. {
  253. _targetVelocity.Y -= FallAcceleration * (float)delta;
  254. }
  255. // Moving the character
  256. Velocity = _targetVelocity;
  257. MoveAndSlide();
  258. }
  259. }
  260. Testing our player's movement
  261. -----------------------------
  262. We're going to put our player in the ``Main`` scene to test it. To do so, we need
  263. to instantiate the player and then add a camera. Unlike in 2D, in 3D, you won't
  264. see anything if your viewport doesn't have a camera pointing at something.
  265. Save your ``Player`` scene and open the ``Main`` scene. You can click on the *Main*
  266. tab at the top of the editor to do so.
  267. |image1|
  268. If you closed the scene before, head to the *FileSystem* dock and double-click
  269. ``main.tscn`` to re-open it.
  270. To instantiate the ``Player``, right-click on the ``Main`` node and select *Instantiate
  271. Child Scene*.
  272. |image2|
  273. In the popup, double-click ``player.tscn``. The character should appear in the
  274. center of the viewport.
  275. Adding a camera
  276. ~~~~~~~~~~~~~~~
  277. Let's add the camera next. Like we did with our *Player*\ 's *Pivot*, we're
  278. going to create a basic rig. Right-click on the ``Main`` node again and select
  279. *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.
  280. |image3|
  281. Notice the *Preview* checkbox that appears in the top-left when you have the
  282. *Camera* selected. You can click it to preview the in-game camera projection.
  283. |image4|
  284. We're going to use the *Pivot* to rotate the camera as if it was on a crane.
  285. Let's first split the 3D view to be able to freely navigate the scene and see
  286. what the camera sees.
  287. In the toolbar right above the viewport, click on *View*, then *2 Viewports*.
  288. You can also press :kbd:`Ctrl + 2` (:kbd:`Cmd + 2` on macOS).
  289. |image11|
  290. |image5|
  291. On the bottom view, select your :ref:`Camera3D <class_Camera3D>` and turn on camera Preview by clicking
  292. the checkbox.
  293. |image6|
  294. In the top view, move the camera about ``19`` units on the Z axis (the blue
  295. one).
  296. |image7|
  297. Here's where the magic happens. Select the *CameraPivot* and rotate it ``-45``
  298. degrees around the X axis (using the red circle). You'll see the camera move as
  299. if it was attached to a crane.
  300. |image8|
  301. You can run the scene by pressing :kbd:`F6` and press the arrow keys to move the
  302. character.
  303. |image9|
  304. We can see some empty space around the character due to the perspective
  305. projection. In this game, we're going to use an orthographic projection instead
  306. to better frame the gameplay area and make it easier for the player to read
  307. distances.
  308. Select the *Camera* again and in the *Inspector*, set the *Projection* to
  309. *Orthogonal* and the *Size* to ``19``. The character should now look flatter and
  310. the ground should fill the background.
  311. .. note::
  312. When using an orthogonal camera in Godot 4, directional shadow quality is
  313. dependent on the camera's *Far* value. The higher the *Far* value, the
  314. further away the camera will be able to see. However, higher *Far* values
  315. also decrease shadow quality as the shadow rendering has to cover a greater
  316. distance.
  317. If directional shadows look too blurry after switching to an orthogonal
  318. camera, decrease the camera's *Far* property to a lower value such as
  319. ``100``. Don't decrease this *Far* property too much, or objects in the
  320. distance will start disappearing.
  321. |image10|
  322. Test your scene and you should be able to move in all 8 directions and not glitch through the floor!
  323. Ultimately, we have both player movement and the view in place. Next, we will
  324. work on the monsters.
  325. .. |image0| image:: img/03.player_movement_code/01.attach_script_to_player.webp
  326. .. |image1| image:: img/03.player_movement_code/02.clicking_main_tab.png
  327. .. |image2| image:: img/03.player_movement_code/03.instance_child_scene.webp
  328. .. |image3| image:: img/03.player_movement_code/04.scene_tree_with_camera.webp
  329. .. |image4| image:: img/03.player_movement_code/05.camera_preview_checkbox.png
  330. .. |image5| image:: img/03.player_movement_code/06.two_viewports.png
  331. .. |image6| image:: img/03.player_movement_code/07.camera_preview_checkbox.png
  332. .. |image7| image:: img/03.player_movement_code/08.camera_moved.png
  333. .. |image8| image:: img/03.player_movement_code/09.camera_rotated.png
  334. .. |image9| image:: img/03.player_movement_code/10.camera_perspective.png
  335. .. |image10| image:: img/03.player_movement_code/13.camera3d_values.webp
  336. .. |image11| image:: img/03.player_movement_code/12.viewport_change.webp