scripting_continued.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 int _accum;
  52. public override void _Process(float delta)
  53. {
  54. _accum++;
  55. Text = _accum.ToString();
  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 fictional 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>` documentation is currently incomplete,
  99. though more will be added later.
  100. Notifications
  101. -------------
  102. Godot has a system of notifications. These are usually not needed for
  103. scripting, as it's too low-level and virtual functions are provided for
  104. most of them. It's just good to know they exist. For example,
  105. you may add an
  106. :ref:`Object._notification() <class_Object__notification>`
  107. function in your script:
  108. .. tabs::
  109. .. code-tab:: gdscript GDScript
  110. func _notification(what):
  111. match what:
  112. NOTIFICATION_READY:
  113. print("This is the same as overriding _ready()...")
  114. NOTIFICATION_PROCESS:
  115. print("This is the same as overriding _process()...")
  116. .. code-tab:: csharp
  117. public override void _Notification(int what)
  118. {
  119. base._Notification(what);
  120. switch (what)
  121. {
  122. case NotificationReady:
  123. GD.Print("This is the same as overriding _Ready()...");
  124. break;
  125. case NotificationProcess:
  126. var delta = GetProcessDeltaTime();
  127. GD.Print("This is the same as overriding _Process()...");
  128. break;
  129. }
  130. }
  131. The documentation of each class in the :ref:`Class Reference <toc-class-ref>`
  132. shows the notifications it can receive. However, in most cases GDScript
  133. provides simpler overrideable functions.
  134. Overrideable functions
  135. ----------------------
  136. Such overrideable functions, which are described as
  137. follows, can be applied to nodes:
  138. .. tabs::
  139. .. code-tab:: gdscript GDScript
  140. func _enter_tree():
  141. # When the node enters the _Scene Tree_, it becomes active
  142. # and this function is called. Children nodes have not entered
  143. # the active scene yet. In general, it's better to use _ready()
  144. # for most cases.
  145. pass
  146. func _ready():
  147. # This function is called after _enter_tree, but it ensures
  148. # that all children nodes have also entered the _Scene Tree_,
  149. # and became active.
  150. pass
  151. func _exit_tree():
  152. # When the node exits the _Scene Tree_, this function is called.
  153. # Children nodes have all exited the _Scene Tree_ at this point
  154. # and all became inactive.
  155. pass
  156. func _process(delta):
  157. # This function is called every frame.
  158. pass
  159. func _physics_process(delta):
  160. # This is called every physics frame.
  161. pass
  162. .. code-tab:: csharp
  163. public override void _EnterTree()
  164. {
  165. // When the node enters the _Scene Tree_, it becomes active
  166. // and this function is called. Children nodes have not entered
  167. // the active scene yet. In general, it's better to use _ready()
  168. // for most cases.
  169. base._EnterTree();
  170. }
  171. public override void _Ready()
  172. {
  173. // This function is called after _enter_tree, but it ensures
  174. // that all children nodes have also entered the _Scene Tree_,
  175. // and became active.
  176. base._Ready();
  177. }
  178. public override void _ExitTree()
  179. {
  180. // When the node exits the _Scene Tree_, this function is called.
  181. // Children nodes have all exited the _Scene Tree_ at this point
  182. // and all became inactive.
  183. base._ExitTree();
  184. }
  185. public override void _Process(float delta)
  186. {
  187. // This function is called every frame.
  188. base._Process(delta);
  189. }
  190. public override void _PhysicsProcess(float delta)
  191. {
  192. // This is called every physics frame.
  193. base._PhysicsProcess(delta);
  194. }
  195. As mentioned before, it's better to use these functions instead of
  196. the notification system.
  197. Creating nodes
  198. --------------
  199. To create a node from code, call the ``.new()`` method, just like for any
  200. other class-based datatype. For example:
  201. .. tabs::
  202. .. code-tab:: gdscript GDScript
  203. var s
  204. func _ready():
  205. s = Sprite.new() # create a new sprite!
  206. add_child(s) # add it as a child of this node
  207. .. code-tab:: csharp
  208. private Sprite _sprite;
  209. public override void _Ready()
  210. {
  211. base._Ready();
  212. _sprite = new Sprite(); // create a new sprite!
  213. AddChild(_sprite); // add it as a child of this node
  214. }
  215. To delete a node, be it inside or outside the scene, ``free()`` must be
  216. used:
  217. .. tabs::
  218. .. code-tab:: gdscript GDScript
  219. func _someaction():
  220. s.free() # immediately removes the node from the scene and frees it
  221. .. code-tab:: csharp
  222. public void _SomeAction()
  223. {
  224. _sprite.Free();
  225. }
  226. When a node is freed, it also frees all its children nodes. Because of
  227. this, manually deleting nodes is much simpler than it appears. Just free
  228. the base node and everything else in the subtree goes away with it.
  229. A situation might occur where we want to delete a node that
  230. is currently "blocked", because it is emitting a signal or calling a
  231. function. This will crash the game. Running Godot
  232. with the debugger will often catch this case and warn you about it.
  233. The safest way to delete a node is by using
  234. :ref:`Node.queue_free() <class_Node_queue_free>`.
  235. This erases the node safely during idle.
  236. .. tabs::
  237. .. code-tab:: gdscript GDScript
  238. func _someaction():
  239. s.queue_free() # immediately removes the node from the scene and frees it
  240. .. code-tab:: csharp
  241. public void _SomeAction()
  242. {
  243. _sprite.QueueFree(); // immediately removes the node from the scene and frees it
  244. }
  245. Instancing scenes
  246. -----------------
  247. Instancing a scene from code is done in two steps. The
  248. first one is to load the scene from your hard drive:
  249. .. tabs::
  250. .. code-tab:: gdscript GDScript
  251. var scene = load("res://myscene.tscn") # will load when the script is instanced
  252. .. code-tab:: csharp
  253. var scene = (PackedScene)ResourceLoader.Load("res://myscene.tscn"); // will load when the script is instanced
  254. Preloading it can be more convenient, as it happens at parse
  255. time:
  256. ::
  257. var scene = preload("res://myscene.tscn") # will load when parsing the script
  258. But ``scene`` is not yet a node. It's packed in a
  259. special resource called :ref:`PackedScene <class_PackedScene>`.
  260. To create the actual node, the function
  261. :ref:`PackedScene.instance() <class_PackedScene_instance>`
  262. must be called. This will return the tree of nodes that can be added to
  263. the active scene:
  264. .. tabs::
  265. .. code-tab:: gdscript GDScript
  266. var node = scene.instance()
  267. add_child(node)
  268. .. code-tab:: csharp
  269. var node = scene.Instance();
  270. AddChild(node);
  271. The advantage of this two-step process is that a packed scene may be
  272. kept loaded and ready to use so that you can create as many
  273. instances as desired. This is especially useful to quickly instance
  274. several enemies, bullets, and other entities in the active scene.