scripting_continued.rst 12 KB

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