scripting_continued.rst 11 KB

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