scripting_continued.rst 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. Additionally, a
  8. lot can be done with animation players.
  9. However, it is still a very common case to have a script process on every
  10. frame. There are two types of processing: idle processing and physics
  11. processing.
  12. Idle processing is activated automatically when the method :ref:`Node._process() <class_Node__process>`
  13. is found in a script. It can be turned off (and back on) with the
  14. :ref:`Node.set_process() <class_Node_set_process>` function.
  15. This method will be called every frame drawn, so it's fully depend on the
  16. frames per second (FPS) of the application:
  17. ::
  18. func _process(delta):
  19. # do something...
  20. The delta parameter describes the time elapsed (in seconds, as a
  21. floating point) since the previous call to "_process()".
  22. Physics processing is similar, but it should be used for all the processes that
  23. must happen before each physics step. For example, to move a character.
  24. It always runs before a physics step and it is called at fixed time intervals,
  25. 60 times per second by default. Change the value in the Project Settings.
  26. The function _process() instead is not synced with physics. Its frame rate is not constant and dependent on hardware and game optimization.
  27. Its execution is done after the physics step on single thread games.
  28. A simple way to test this is to create a scene with a single Label node,
  29. with the following script:
  30. ::
  31. extends Label
  32. var accum=0
  33. func _process(delta):
  34. accum += delta
  35. text = str(accum) # text is a built-in label property
  36. Which will show a counter increasing each frame.
  37. Groups
  38. ------
  39. Nodes can be added to groups (as many as desired per node). This is a
  40. simple yet useful feature for organizing large scenes. There are two
  41. ways to do this: the first is from the UI, from the Groups button under the Node panel:
  42. .. image:: img/groups_in_nodes.PNG
  43. And the second from code. One useful example would be to tag scenes
  44. which are enemies.
  45. ::
  46. func _ready():
  47. add_to_group("enemies")
  48. This way, if the player is discovered sneaking into the secret base,
  49. all enemies can be notified about the alarm sounding, by using
  50. :ref:`SceneTree.call_group() <class_SceneTree_call_group>`:
  51. ::
  52. func _on_discovered(): # this is a fictional function
  53. get_tree().call_group("enemies", "player_was_discovered")
  54. The above code calls the function "player_was_discovered" on every
  55. member of the group "enemies".
  56. Optionally, it is possible to get the full list of "enemies" nodes by
  57. calling
  58. :ref:`SceneTree.get_nodes_in_group() <class_SceneTree_get_nodes_in_group>`:
  59. ::
  60. var enemies = get_tree().get_nodes_in_group("enemies")
  61. More will be added about
  62. :ref:`SceneTree <class_SceneTree>`
  63. later.
  64. Notifications
  65. -------------
  66. Godot has a system of notifications. This is usually not needed for
  67. scripting, as it's too low level and virtual functions are provided for
  68. most of them. It's just good to know they exist. Simply
  69. add a
  70. :ref:`Object._notification() <class_Object__notification>`
  71. function in your script:
  72. ::
  73. func _notification(what):
  74. if (what == NOTIFICATION_READY):
  75. print("This is the same as overriding _ready()...")
  76. elif (what == NOTIFICATION_PROCESS):
  77. var delta = get_process_time()
  78. print("This is the same as overriding _process()...")
  79. The documentation of each class in the :ref:`Class Reference <toc-class-ref>`
  80. shows the notifications it can receive. However, for most cases GDScript
  81. provides simpler overrideable functions.
  82. Overrideable functions
  83. ----------------------
  84. Nodes provide many useful overrideable functions, which are described as
  85. follows:
  86. ::
  87. func _enter_tree():
  88. # When the node enters the _Scene Tree_, it becomes active
  89. # and this function is called. Children nodes have not entered
  90. # the active scene yet. In general, it's better to use _ready()
  91. # for most cases.
  92. pass
  93. func _ready():
  94. # This function is called after _enter_tree, but it ensures
  95. # that all children nodes have also entered the _Scene Tree_,
  96. # and became active.
  97. pass
  98. func _exit_tree():
  99. # When the node exits the _Scene Tree_, this function is called.
  100. # Children nodes have all exited the _Scene Tree_ at this point
  101. # and all became inactive.
  102. pass
  103. func _process(delta):
  104. # This function is called every frame.
  105. pass
  106. func _physics_process(delta):
  107. # This is called every physics frame.
  108. pass
  109. func _paused():
  110. # Called when game is paused. After this call, the node will not receive
  111. # any more process callbacks.
  112. pass
  113. func _unpaused():
  114. # Called when game is unpaused.
  115. pass
  116. As mentioned before, it's best to use these functions.
  117. Creating nodes
  118. --------------
  119. To create a node from code, call the .new() method, just like for any
  120. other class based datatype. Example:
  121. ::
  122. var s
  123. func _ready():
  124. s = Sprite.new() # create a new sprite!
  125. add_child(s) # add it as a child of this node
  126. To delete a node, be it inside or outside the scene, "free()" must be
  127. used:
  128. ::
  129. func _someaction():
  130. s.free() # immediately removes the node from the scene and frees it
  131. When a node is freed, it also frees all its children nodes. Because of
  132. this, manually deleting nodes is much simpler than it appears. Just free
  133. the base node and everything else in the sub-tree goes away with it.
  134. However, it might happen very often that we want to delete a node that
  135. is currently "blocked", because it is emitting a signal or calling a
  136. function. This will result in crashing the game. Running Godot
  137. in the debugger often will catch this case and warn you about it.
  138. The safest way to delete a node is by using
  139. :ref:`Node.queue_free() <class_Node_queue_free>`.
  140. This erases the node safely during idle.
  141. ::
  142. func _someaction():
  143. s.queue_free() # remove the node and delete it while nothing is happening
  144. Instancing scenes
  145. -----------------
  146. Instancing a scene from code is pretty easy and done in two steps. The
  147. first one is to load the scene from disk.
  148. ::
  149. var scene = load("res://myscene.tscn") # will load when the script is instanced
  150. Preloading it can be more convenient sometimes, as it happens at parse
  151. time.
  152. ::
  153. var scene = preload("res://myscene.tscn") # will load when parsing the script
  154. But 'scene' is not yet a node for containing subnodes. It's packed in a
  155. special resource called :ref:`PackedScene <class_PackedScene>`.
  156. To create the actual node, the function
  157. :ref:`PackedScene.instance() <class_PackedScene_instance>`
  158. must be called. This will return the tree of nodes that can be added to
  159. the active scene:
  160. ::
  161. var node = scene.instance()
  162. add_child(node)
  163. The advantage of this two-step process is that a packed scene may be
  164. kept loaded and ready to use, so it can be used to create as many
  165. instances as desired. This is especially useful to quickly instance
  166. several enemies, bullets, etc., in the active scene.