scripting_first_script.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. :article_outdated: True
  2. ..
  3. Intention:
  4. - Giving a *short* and sweet hands-on intro to GDScript. The page should
  5. focus on working in the code editor.
  6. - We assume the reader has programming foundations. If you don't, consider
  7. taking the course we recommend in the :ref:`introduction to Godot page <doc_learning_programming>`.
  8. Techniques:
  9. - Creating a sprite.
  10. - Creating a script.
  11. - _init() and _process().
  12. - Moving an object on screen.
  13. .. _doc_scripting_first_script:
  14. Creating your first script
  15. ==========================
  16. In this lesson, you will code your first script to make the Godot icon turn in
  17. circles using GDScript. As we mentioned :ref:`in the introduction
  18. <toc-learn-introduction>`, we assume you have programming foundations.
  19. The equivalent C# code has been included in another tab for convenience.
  20. .. image:: img/scripting_first_script_rotating_godot.gif
  21. .. seealso:: To learn more about GDScript, its keywords, and its syntax, head to
  22. the :ref:`GDScript reference<doc_gdscript>`.
  23. .. seealso:: To learn more about C#, head to the :ref:`C# basics <doc_c_sharp>` page.
  24. Project setup
  25. -------------
  26. Please :ref:`create a new project <doc_creating_and_importing_projects>` to
  27. start with a clean slate. Your project should contain one picture: the Godot
  28. icon, which we often use for prototyping in the community.
  29. .. Godot icon
  30. We need to create a Sprite2D node to display it in the game. In the Scene dock,
  31. click the Other Node button.
  32. .. image:: img/scripting_first_script_click_other_node.png
  33. Type "Sprite2D" in the search bar to filter nodes and double-click on Sprite2D
  34. to create the node.
  35. .. image:: img/scripting_first_script_add_sprite_node.webp
  36. Your Scene tab should now only have a Sprite2D node.
  37. .. image:: img/scripting_first_script_scene_tree.webp
  38. A Sprite2D node needs a texture to display. In the Inspector on the right, you
  39. can see that the Texture property says "[empty]". To display the Godot icon,
  40. click and drag the file ``icon.svg`` from the FileSystem dock onto the Texture
  41. slot.
  42. .. image:: img/scripting_first_script_setting_texture.webp
  43. .. note::
  44. You can create Sprite2D nodes automatically by dragging and dropping images
  45. on the viewport.
  46. .. image:: img/scripting_first_script_dragging_sprite.png
  47. Then, click and drag the icon in the viewport to center it in the game view.
  48. .. image:: img/scripting_first_script_centering_sprite.png
  49. Creating a new script
  50. ---------------------
  51. To create and attach a new script to our node, right-click on Sprite2D in the
  52. scene dock and select "Attach Script".
  53. .. image:: img/scripting_first_script_attach_script.webp
  54. The Attach Node Script window appears. It allows you to select the script's
  55. language and file path, among other options.
  56. Change the Template field from "Node: Default" to "Object: Empty" to start with a clean file. Leave the
  57. other options by default and click the Create button to create the script.
  58. .. image:: img/scripting_first_script_attach_node_script.webp
  59. The Script workspace should appear with your new ``sprite_2d.gd`` file open and
  60. the following line of code:
  61. .. tabs::
  62. .. code-tab:: gdscript GDScript
  63. extends Sprite2D
  64. .. code-tab:: csharp C#
  65. using Godot;
  66. public partial class MySprite2D : Sprite2D
  67. {
  68. }
  69. Every GDScript file is implicitly a class. The ``extends`` keyword defines the
  70. class this script inherits or extends. In this case, it's ``Sprite2D``, meaning
  71. our script will get access to all the properties and functions of the Sprite2D
  72. node, including classes it extends, like ``Node2D``, ``CanvasItem``, and
  73. ``Node``.
  74. .. note:: In GDScript, if you omit the line with the ``extends`` keyword, your
  75. class will implicitly extend :ref:`RefCounted <class_RefCounted>`, which
  76. Godot uses to manage your application's memory.
  77. Inherited properties include the ones you can see in the Inspector dock, like
  78. our node's ``texture``.
  79. .. note::
  80. By default, the Inspector displays a node's properties in "Title Case", with
  81. capitalized words separated by a space. In GDScript code, these properties
  82. are in "snake_case", which is lowercase with words separated by an underscore.
  83. You can hover over any property's name in the Inspector to see a description and
  84. its identifier in code.
  85. Hello, world!
  86. -------------
  87. Our script currently doesn't do anything. Let's make it print the text "Hello,
  88. world!" to the Output bottom panel to get started.
  89. Add the following code to your script:
  90. .. tabs::
  91. .. code-tab:: gdscript GDScript
  92. func _init():
  93. print("Hello, world!")
  94. .. code-tab:: csharp C#
  95. public MySprite2D()
  96. {
  97. GD.Print("Hello, world!");
  98. }
  99. Let's break it down. The ``func`` keyword defines a new function named
  100. ``_init``. This is a special name for our class's constructor. The engine calls
  101. ``_init()`` on every object or node upon creating it in memory, if you define
  102. this function.
  103. .. note:: GDScript is an indent-based language. The tab at the start of the line
  104. that says ``print()`` is necessary for the code to work. If you omit
  105. it or don't indent a line correctly, the editor will highlight it in
  106. red and display the following error message: "Indented block expected".
  107. Save the scene as ``sprite_2d.tscn`` if you haven't already, then press :kbd:`F6` (:kbd:`Cmd + R` on macOS)
  108. to run it. Look at the **Output** bottom panel that expands.
  109. It should display "Hello, world!".
  110. .. image:: img/scripting_first_script_print_hello_world.png
  111. Delete the ``_init()`` function, so you're only left with the line ``extends
  112. Sprite2D``.
  113. Turning around
  114. --------------
  115. It's time to make our node move and rotate. To do so, we're going to add two
  116. member variables to our script: the movement speed in pixels per second and the
  117. angular speed in radians per second. Add the following after the ``extends Sprite2D`` line.
  118. .. tabs::
  119. .. code-tab:: gdscript GDScript
  120. var speed = 400
  121. var angular_speed = PI
  122. .. code-tab:: csharp C#
  123. private int _speed = 400;
  124. private float _angularSpeed = Mathf.Pi;
  125. Member variables sit near the top of the script, after any "extends" lines,
  126. but before functions. Every node
  127. instance with this script attached to it will have its own copy of the ``speed``
  128. and ``angular_speed`` properties.
  129. .. note:: Angles in Godot work in radians by default,
  130. but you have built-in functions and properties available if you prefer
  131. to calculate angles in degrees instead.
  132. To move our icon, we need to update its position and rotation every frame in the
  133. game loop. We can use the ``_process()`` virtual function of the ``Node`` class.
  134. If you define it in any class that extends the Node class, like Sprite2D, Godot
  135. will call the function every frame and pass it an argument named ``delta``, the
  136. time elapsed since the last frame.
  137. .. note::
  138. Games work by rendering many images per second, each called a frame, and
  139. they do so in a loop. We measure the rate at which a game produces images in
  140. Frames Per Second (FPS). Most games aim for 60 FPS, although you might find
  141. figures like 30 FPS on slower mobile devices or 90 to 240 for virtual
  142. reality games.
  143. The engine and game developers do their best to update the game world and
  144. render images at a constant time interval, but there are always small
  145. variations in frame render times. That's why the engine provides us with
  146. this delta time value, making our motion independent of our framerate.
  147. At the bottom of the script, define the function:
  148. .. tabs::
  149. .. code-tab:: gdscript GDScript
  150. func _process(delta):
  151. rotation += angular_speed * delta
  152. .. code-tab:: csharp C#
  153. public override void _Process(double delta)
  154. {
  155. Rotation += _angularSpeed * (float)delta;
  156. }
  157. The ``func`` keyword defines a new function. After it, we have to write the
  158. function's name and arguments it takes in parentheses. A colon ends the
  159. definition, and the indented blocks that follow are the function's content or
  160. instructions.
  161. .. note:: Notice how ``_process()``, like ``_init()``, starts with a leading
  162. underscore. By convention, Godot's virtual functions, that is to say,
  163. built-in functions you can override to communicate with the engine,
  164. start with an underscore.
  165. The line inside the function, ``rotation += angular_speed * delta``, increments
  166. our sprite's rotation every frame. Here, ``rotation`` is a property inherited
  167. from the class ``Node2D``, which ``Sprite2D`` extends. It controls the rotation
  168. of our node and works with radians.
  169. .. tip:: In the code editor, you can ctrl-click on any built-in property or
  170. function like ``position``, ``rotation``, or ``_process`` to open the
  171. corresponding documentation in a new tab.
  172. Run the scene to see the Godot icon turn in-place.
  173. .. image:: img/scripting_first_script_godot_turning_in_place.gif
  174. .. note:: In C#, notice how the ``delta`` argument taken by ``_Process()`` is a
  175. ``double``. We therefore need to convert it to ``float`` when we apply
  176. it to the rotation.
  177. Moving forward
  178. ~~~~~~~~~~~~~~
  179. Let's now make the node move. Add the following two lines inside of the ``_process()``
  180. function, ensuring the new lines are indented the same way as the ``rotation += angular_speed * delta`` line before
  181. them.
  182. .. tabs::
  183. .. code-tab:: gdscript GDScript
  184. var velocity = Vector2.UP.rotated(rotation) * speed
  185. position += velocity * delta
  186. .. code-tab:: csharp C#
  187. var velocity = Vector2.Up.Rotated(Rotation) * _speed;
  188. Position += velocity * (float)delta;
  189. As we already saw, the ``var`` keyword defines a new variable. If you put it at
  190. the top of the script, it defines a property of the class. Inside a function, it
  191. defines a local variable: it only exists within the function's scope.
  192. We define a local variable named ``velocity``, a 2D vector representing both a
  193. direction and a speed. To make the node move forward, we start from the Vector2
  194. class's constant ``Vector2.UP``, a vector pointing up, and rotate it by calling the
  195. ``rotated()`` method on any ``Vector2``. This expression, ``Vector2.UP.rotated(rotation)``,
  196. is a vector pointing forward relative to our icon. Multiplied by our ``speed``
  197. property, it gives us a velocity we can use to move the node forward.
  198. We add ``velocity * delta`` to the node's ``position`` to move it. The position
  199. itself is of type :ref:`Vector2 <class_Vector2>`, a built-in type in Godot
  200. representing a 2D vector.
  201. Run the scene to see the Godot head run in circles.
  202. .. image:: img/scripting_first_script_rotating_godot.gif
  203. .. note:: Moving a node like that does not take into account colliding with
  204. walls or the floor. In :ref:`doc_your_first_2d_game`, you will learn
  205. another approach to moving objects while detecting collisions.
  206. Our node currently moves by itself. In the next part
  207. :ref:`doc_scripting_player_input`, we'll use player input to control it.
  208. Complete script
  209. ---------------
  210. Here is the complete ``sprite_2d.gd`` file for reference.
  211. .. tabs::
  212. .. code-tab:: gdscript GDScript
  213. extends Sprite2D
  214. var speed = 400
  215. var angular_speed = PI
  216. func _process(delta):
  217. rotation += angular_speed * delta
  218. var velocity = Vector2.UP.rotated(rotation) * speed
  219. position += velocity * delta
  220. .. code-tab:: csharp C#
  221. using Godot;
  222. public partial class MySprite2D : Sprite2D
  223. {
  224. private int _speed = 400;
  225. private float _angularSpeed = Mathf.Pi;
  226. public override void _Process(double delta)
  227. {
  228. Rotation += _angularSpeed * (float)delta;
  229. var velocity = Vector2.Up.Rotated(Rotation) * _speed;
  230. Position += velocity * (float)delta;
  231. }
  232. }