scripting.rst 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. .. _doc_scripting:
  2. Scripting
  3. =========
  4. Introduction
  5. ------------
  6. Much has been said about tools that allow users to create video games
  7. without programming. This appeals to many people who would love to be able to
  8. make a game without having to learn how to code. This need has been around for
  9. a long time, even inside game companies, where game designers would like to
  10. have more control of their game's flow.
  11. Many products have been shipped promising such a no-programming environment,
  12. but the results often fall short of expectations. The projects they produce end
  13. up being too complex or require solutions that are too inefficient compared to
  14. what could have been accomplished with traditional code.
  15. As a result, we think that programming is here to stay. In fact, game engines
  16. have been moving in this direction, adding tools that try to reduce the amount
  17. of code that needs to be written rather than eliminating it. The engine can
  18. provide many general solutions, while the developer can use code to accomplish
  19. specific tasks.
  20. Godot has embraced this goal from the beginning, and it has influenced many of
  21. its design decisions. First and foremost is the scene system. This system has
  22. many benefits, but fundamentally its goal is to relieve programmers from the
  23. responsibility of having to implement an overall architecture.
  24. When designing games using the scene system, the whole project is fragmented
  25. into *complementary* scenes (not individual ones). Scenes complement
  26. (i.e. help) each other, instead of being separate. There will be plenty of
  27. examples of this later on, but it's very important to remember it.
  28. GDScript
  29. --------
  30. :ref:`doc_gdscript` is a dynamically typed scripting language which was
  31. designed with the following goals:
  32. - Most importantly, it should feel simple, familiar, and as easy to learn as
  33. possible.
  34. - It should have a syntax that's very readable. The syntax is mostly borrowed
  35. from Python.
  36. - It should integrate tightly with Godot itself, for example sharing its memory
  37. model, taking advantage of the scene/node system, and exposing useful
  38. game-related classes already part of the Godot engine.
  39. Programmers generally take a few days to learn GDScript and feel comfortable
  40. with it within two weeks.
  41. As with most dynamically typed languages, the higher productivity (code is
  42. easier to learn, faster to write, no compilation, etc.) is balanced with a
  43. performance penalty. However, keep in mind that most critical code is already
  44. written in C++ in the engine (vector ops, physics, math, indexing, etc.), which
  45. results in more than sufficient performance for most types of games.
  46. In any case, if more performance is required, critical sections can be
  47. rewritten in C++ and registered with Godot, which in turn exposes them to all
  48. scripts. In this way, you can write a class in GDScript first but convert it to
  49. a C++ class later, and the rest of the game will work the same as before.
  50. Finally, note that GDScript provides the powerful
  51. `extend <http://c2.com/cgi/wiki?EmbedVsExtend>`__ keyword. Many classes in the
  52. Godot engine are available as base classes to be extended from.
  53. Scripting a scene
  54. -----------------
  55. In the rest of this tutorial, we'll set up a simple GUI scene consisting of a
  56. button and a label, where pressing the button will update the label. This will
  57. demonstrate:
  58. - how to write a basic script and attach it to a node
  59. - how to hook up UI elements via *signals*
  60. - how to write a script that can access other nodes in the scene
  61. Before continuing, please make sure to read the :ref:`doc_gdscript` reference.
  62. It's a simple language and the reference is short, so it will not take more
  63. than a few minutes to get an overview of the concepts.
  64. Scene setup
  65. ~~~~~~~~~~~
  66. Use the add node dialog to create the following hierarchy, with the following
  67. nodes:
  68. - Panel
  69. * Label
  70. * Button
  71. It should look like this in the scene tree:
  72. .. image:: /img/scripting_scene_tree.png
  73. Use the 2D editor to position and resize the button and label so that they
  74. look like the image below. You can set the text in the Inspector pane.
  75. .. image:: /img/label_button_example.png
  76. Finally, save the scene, with a name such as "sayhello.tscn"
  77. .. _doc_scripting-adding_a_script:
  78. Adding a script
  79. ~~~~~~~~~~~~~~~
  80. Right click on the panel node, and then select "Add Script" in the context
  81. menu:
  82. .. image:: /img/add_script.png
  83. The script creation dialog will pop up. This dialog allows you to set the
  84. language, class name, and other relevant options.
  85. Actually, in GDScript, the file itself represents the class, so in this case,
  86. the class name field is not editable.
  87. The node we're attaching the script to is a panel, so the "Inherits" field
  88. should automatically be filled in with "Panel". This is what we want as our
  89. script's goal is to extend this panel node's functionality.
  90. Finally, enter a path name for the script and select "Create":
  91. .. image:: /img/script_create.png
  92. Once this is done, the script will be created and added to the node. You can
  93. see this both as an extra icon in the node as well as in the script property:
  94. .. image:: /img/script_added.png
  95. To edit the script, select either of the highlighted buttons. This will bring
  96. you to the script editor where an existing template will be included by default:
  97. .. image:: /img/script_template.png
  98. There is not much in there. The "_ready()" function is called when the
  99. node (and all its children) enter the active scene. (Note: "_ready()" is not
  100. the a constructor; the constructor is "_init()").
  101. The role of the script
  102. ~~~~~~~~~~~~~~~~~~~~~~
  103. A script adds behavior to a node. It is used to control how the node functions
  104. as well as how it interacts with other nodes (children, parent, siblings,
  105. etc.). The local scope of the script is the node. In other words, the script
  106. inherits the functions provided by that node.
  107. .. image:: /img/brainslug.jpg
  108. Handling a signal
  109. ~~~~~~~~~~~~~~~~~
  110. Signals are "emitted" when some specific kind of action happens, and they can be
  111. connected to any function of any script instance. Signals are used mostly in
  112. GUI nodes (although other nodes have them too, and you can even define custom
  113. signals in your own scripts).
  114. In this step, we'll connect the "pressed" signal to a custom function.
  115. The editor provides an interface for connecting signals to your scripts. You
  116. can access this by selecting the node in the scene tree and then selecting the
  117. "Node" tab. Next, make sure that you have "Signals" selected.
  118. .. image:: /img/signals.png
  119. At this point, you could use the visual interface to hook up the "pressed"
  120. signal by double clicking on it and selecting a target node that already has a
  121. script attached to it. But for the sake of learning, we're going to code up the
  122. connection manually.
  123. To accomplish this, we will introduce a function that is probably the most used
  124. by Godot programmers, namely :ref:`Node.get_node() <class_Node_get_node>`.
  125. This function uses paths to fetch nodes anywhere in the scene, relative to the
  126. node that owns the script.
  127. In our case, because the button and the label are siblings under the panel
  128. where the script is attached, you can fetch the button as follows:
  129. ::
  130. get_node("Button")
  131. Next, write a function which will be called when the button is pressed:
  132. ::
  133. func _on_button_pressed():
  134. get_node("Label").set_text("HELLO!")
  135. Finally, connect the button's "pressed" signal to that callback in _ready(), by
  136. using :ref:`Object.connect() <class_Object_connect>`.
  137. ::
  138. func _ready():
  139. get_node("Button").connect("pressed",self,"_on_button_pressed")
  140. The final script should look basically like this:
  141. ::
  142. extends Panel
  143. func _on_button_pressed():
  144. get_node("Label").set_text("HELLO!")
  145. func _ready():
  146. get_node("Button").connect("pressed",self,"_on_button_pressed")
  147. Run the scene and press the button. You should get the following result:
  148. .. image:: /img/scripting_hello.png
  149. Why hello there! Congratulations on scripting your first scene.
  150. **Note:** A common misunderstanding in this tutorial is how get_node(path)
  151. works. For some given node, get_node(path) searches its immediate children.
  152. In the above code, this means that *Button* must be a child of *Panel*. If
  153. *Button* were instead a child of *Label*, the code to obtain it would be:
  154. ::
  155. # not for this case
  156. # but just in case
  157. get_node("Label/Button")
  158. Also, remember that nodes are referenced by name, not by type.