scripting_first_script.rst 11 KB

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