scripting_continued.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. .. _doc_scripting_continued:
  2. Scripting (continued)
  3. =====================
  4. Processing
  5. ----------
  6. Several actions in Godot are triggered by callbacks or virtual functions,
  7. so there is no need to write code that runs all the time.
  8. However, it is still common to need a script to be processed on every
  9. frame. There are two types of processing: idle processing and physics
  10. processing.
  11. Idle processing is activated when the method :ref:`Node._process() <class_Node__process>`
  12. is found in a script. It can be turned off and on with the
  13. :ref:`Node.set_process() <class_Node_set_process>` function.
  14. This method will be called every time a frame is drawn, so it's fully dependent on
  15. how many frames per second (FPS) the application is running at:
  16. .. tabs::
  17. .. code-tab:: gdscript GDScript
  18. func _process(delta):
  19. # Do something...
  20. pass
  21. .. code-tab:: csharp
  22. public override void _Process(float delta)
  23. {
  24. // Do something...
  25. }
  26. The delta parameter contains the time elapsed in seconds, as a
  27. floating point, since the previous call to ``_process()``.
  28. This parameter can be used to make sure things always take the same
  29. amount of time, regardless of the game's FPS.
  30. For example, movement is often multiplied with a time delta to make movement
  31. speed both constant and independent from the frame rate.
  32. Physics processing with ``_physics_process()`` is similar, but it should be used for processes that
  33. must happen before each physics step, such as controlling a character.
  34. It always runs before a physics step and it is called at fixed time intervals:
  35. 60 times per second by default. You can change the interval from the Project Settings, under
  36. Physics -> Common -> Physics Fps.
  37. The function ``_process()``, however, is not synced with physics. Its frame rate is not constant and is dependent
  38. on hardware and game optimization. Its execution is done after the physics step on single-threaded games.
  39. A simple way to test this is to create a scene with a single Label node,
  40. with the following script:
  41. .. tabs::
  42. .. code-tab:: gdscript GDScript
  43. extends Label
  44. var accum = 0
  45. func _process(delta):
  46. accum += delta
  47. text = str(accum) # 'text' is a built-in label property.
  48. .. code-tab:: csharp
  49. public class CustomLabel : Label
  50. {
  51. private float _accum;
  52. public override void _Process(float delta)
  53. {
  54. _accum += delta;
  55. Text = _accum.ToString(); // 'Text' is a built-in label property.
  56. }
  57. }
  58. Which will show a counter increasing each frame.
  59. Groups
  60. ------
  61. Nodes can be added to groups, as many as desired per node, and is a useful feature for organizing large scenes.
  62. There are two ways to do this. The first is from the UI, from the Groups button under the Node panel:
  63. .. image:: img/groups_in_nodes.png
  64. And the second way is from code. One example would be to tag scenes
  65. which are enemies:
  66. .. tabs::
  67. .. code-tab:: gdscript GDScript
  68. func _ready():
  69. add_to_group("enemies")
  70. .. code-tab:: csharp
  71. public override void _Ready()
  72. {
  73. base._Ready();
  74. AddToGroup("enemies");
  75. }
  76. This way, if the player is discovered sneaking into a secret base,
  77. all enemies can be notified about its alarm sounding by using
  78. :ref:`SceneTree.call_group() <class_SceneTree_call_group>`:
  79. .. tabs::
  80. .. code-tab:: gdscript GDScript
  81. func _on_discovered(): # This is a purely illustrative function.
  82. get_tree().call_group("enemies", "player_was_discovered")
  83. .. code-tab:: csharp
  84. public void _OnDiscovered() // This is a purely illustrative function.
  85. {
  86. GetTree().CallGroup("enemies", "player_was_discovered");
  87. }
  88. The above code calls the function ``player_was_discovered`` on every
  89. member of the group ``enemies``.
  90. It is also possible to get the full list of ``enemies`` nodes by
  91. calling
  92. :ref:`SceneTree.get_nodes_in_group() <class_SceneTree_get_nodes_in_group>`:
  93. .. tabs::
  94. .. code-tab:: gdscript GDScript
  95. var enemies = get_tree().get_nodes_in_group("enemies")
  96. .. code-tab:: csharp
  97. var enemies = GetTree().GetNodesInGroup("enemies");
  98. The :ref:`SceneTree <class_SceneTree>` class provides many useful methods,
  99. like interacting with scenes, their node hierarchy and groups of nodes.
  100. It allows you to easily switch scenes or reload them,
  101. to quit the game or pause and unpause it.
  102. It even comes with interesting signals.
  103. So check it out if you got some time!
  104. Notifications
  105. -------------
  106. Godot has a system of notifications. These are usually not needed for
  107. scripting, as it's too low-level and virtual functions are provided for
  108. most of them. It's just good to know they exist. For example,
  109. you may add an
  110. :ref:`Object._notification() <class_Object__notification>`
  111. function in your script:
  112. .. tabs::
  113. .. code-tab:: gdscript GDScript
  114. func _notification(what):
  115. match what:
  116. NOTIFICATION_READY:
  117. print("This is the same as overriding _ready()...")
  118. NOTIFICATION_PROCESS:
  119. print("This is the same as overriding _process()...")
  120. .. code-tab:: csharp
  121. public override void _Notification(int what)
  122. {
  123. base._Notification(what);
  124. switch (what)
  125. {
  126. case NotificationReady:
  127. GD.Print("This is the same as overriding _Ready()...");
  128. break;
  129. case NotificationProcess:
  130. var delta = GetProcessDeltaTime();
  131. GD.Print("This is the same as overriding _Process()...");
  132. break;
  133. }
  134. }
  135. The documentation of each class in the :ref:`Class Reference <toc-class-ref>`
  136. shows the notifications it can receive. However, in most cases GDScript
  137. provides simpler overrideable functions.
  138. Overrideable functions
  139. ----------------------
  140. Such overrideable functions, which are described as
  141. follows, can be applied to nodes:
  142. .. tabs::
  143. .. code-tab:: gdscript GDScript
  144. func _enter_tree():
  145. # When the node enters the _Scene Tree_, it becomes active
  146. # and this function is called. Children nodes have not entered
  147. # the active scene yet. In general, it's better to use _ready()
  148. # for most cases.
  149. pass
  150. func _ready():
  151. # This function is called after _enter_tree, but it ensures
  152. # that all children nodes have also entered the _Scene Tree_,
  153. # and became active.
  154. pass
  155. func _exit_tree():
  156. # When the node exits the _Scene Tree_, this function is called.
  157. # Children nodes have all exited the _Scene Tree_ at this point
  158. # and all became inactive.
  159. pass
  160. func _process(delta):
  161. # This function is called every frame.
  162. pass
  163. func _physics_process(delta):
  164. # This is called every physics frame.
  165. pass
  166. .. code-tab:: csharp
  167. public override void _EnterTree()
  168. {
  169. // When the node enters the _Scene Tree_, it becomes active
  170. // and this function is called. Children nodes have not entered
  171. // the active scene yet. In general, it's better to use _ready()
  172. // for most cases.
  173. base._EnterTree();
  174. }
  175. public override void _Ready()
  176. {
  177. // This function is called after _enter_tree, but it ensures
  178. // that all children nodes have also entered the _Scene Tree_,
  179. // and became active.
  180. base._Ready();
  181. }
  182. public override void _ExitTree()
  183. {
  184. // When the node exits the _Scene Tree_, this function is called.
  185. // Children nodes have all exited the _Scene Tree_ at this point
  186. // and all became inactive.
  187. base._ExitTree();
  188. }
  189. public override void _Process(float delta)
  190. {
  191. // This function is called every frame.
  192. base._Process(delta);
  193. }
  194. public override void _PhysicsProcess(float delta)
  195. {
  196. // This is called every physics frame.
  197. base._PhysicsProcess(delta);
  198. }
  199. As mentioned before, it's better to use these functions instead of
  200. the notification system.
  201. Creating nodes
  202. --------------
  203. To create a node from code, call the ``.new()`` method, like for any
  204. other class-based datatype. For example:
  205. .. tabs::
  206. .. code-tab:: gdscript GDScript
  207. var s
  208. func _ready():
  209. s = Sprite.new() # Create a new sprite!
  210. add_child(s) # Add it as a child of this node.
  211. .. code-tab:: csharp
  212. private Sprite _sprite;
  213. public override void _Ready()
  214. {
  215. base._Ready();
  216. _sprite = new Sprite(); // Create a new sprite!
  217. AddChild(_sprite); // Add it as a child of this node.
  218. }
  219. To delete a node, be it inside or outside the scene, ``free()`` must be
  220. used:
  221. .. tabs::
  222. .. code-tab:: gdscript GDScript
  223. func _someaction():
  224. s.free() # Immediately removes the node from the scene and frees it.
  225. .. code-tab:: csharp
  226. public void _SomeAction()
  227. {
  228. _sprite.Free(); // Immediately removes the node from the scene and frees it.
  229. }
  230. When a node is freed, it also frees all its children nodes. Because of
  231. this, manually deleting nodes is much simpler than it appears. Free
  232. the base node and everything else in the subtree goes away with it.
  233. A situation might occur where we want to delete a node that
  234. is currently "blocked", because it is emitting a signal or calling a
  235. function. This will crash the game. Running Godot
  236. with the debugger will often catch this case and warn you about it.
  237. The safest way to delete a node is by using
  238. :ref:`Node.queue_free() <class_Node_queue_free>`.
  239. This erases the node safely during idle.
  240. .. tabs::
  241. .. code-tab:: gdscript GDScript
  242. func _someaction():
  243. s.queue_free() # Queues the Node for deletion at the end of the current Frame.
  244. .. code-tab:: csharp
  245. public void _SomeAction()
  246. {
  247. _sprite.QueueFree(); // Queues the Node for deletion at the end of the current Frame.
  248. }
  249. Instancing scenes
  250. -----------------
  251. Instancing a scene from code is done in two steps. The
  252. first one is to load the scene from your hard drive:
  253. .. tabs::
  254. .. code-tab:: gdscript GDScript
  255. var scene = load("res://myscene.tscn") # Will load when the script is instanced.
  256. .. code-tab:: csharp
  257. var scene = (PackedScene)ResourceLoader.Load("res://myscene.tscn"); // Will load when the script is instanced.
  258. Preloading it can be more convenient, as it happens at parse
  259. time (GDScript only):
  260. ::
  261. var scene = preload("res://myscene.tscn") # Will load when parsing the script.
  262. But ``scene`` is not yet a node. It's packed in a
  263. special resource called :ref:`PackedScene <class_PackedScene>`.
  264. To create the actual node, the function
  265. :ref:`PackedScene.instance() <class_PackedScene_instance>`
  266. must be called. This will return the tree of nodes that can be added to
  267. the active scene:
  268. .. tabs::
  269. .. code-tab:: gdscript GDScript
  270. var node = scene.instance()
  271. add_child(node)
  272. .. code-tab:: csharp
  273. var node = scene.Instance();
  274. AddChild(node);
  275. The advantage of this two-step process is that a packed scene may be
  276. kept loaded and ready to use so that you can create as many
  277. instances as desired. This is especially useful to quickly instance
  278. several enemies, bullets, and other entities in the active scene.