2
0

gdextension_cpp_example.rst 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. .. _doc_godot_cpp_getting_started:
  2. Getting started
  3. ===============
  4. Workflow overview
  5. -----------------
  6. As a GDExtension, godot-cpp is more complicated to use than :ref:`GDScript <doc_gdscript>` and :ref:`C# <doc_c_sharp>`.
  7. If you decide to work with it, here's what to expect your workflow to look like:
  8. * Create a new godot-cpp project (from the `template <https://github.com/godotengine/godot-cpp-template>`__, or from scratch, as explained below).
  9. * Develop your code with your :ref:`favorite IDE <toc-devel-configuring_an_ide>` locally.
  10. * Build and test your code with the earliest compatible Godot version.
  11. * Create builds for all platforms you want to support (e.g. using `GitHub Actions <https://github.com/godotengine/godot-cpp-template/blob/main/.github/workflows/builds.yml>`__).
  12. * Optional: Publish on the `Godot Asset Library <https://godotengine.org/asset-library/asset>`__.
  13. Example project
  14. ---------------
  15. For your first godot-cpp project, we recommend starting with this guide to understand the technology involved with
  16. godot-cpp. After you're done, you can use the `godot-cpp template <https://github.com/godotengine/godot-cpp-template>`__,
  17. which has better coverage of features, such as a GitHub action pipeline and useful ``SConstruct`` boilerplate code.
  18. However, the template does not explain itself to a high level of detail, which is why we recommend going through this
  19. guide first.
  20. Setting up the project
  21. ----------------------
  22. There are a few prerequisites you'll need:
  23. - A Godot 4 executable.
  24. - A C++ compiler.
  25. - SCons as a build tool.
  26. - A copy of the `godot-cpp repository <https://github.com/godotengine/godot-cpp>`__.
  27. See also :ref:`Configuring an IDE <toc-devel-configuring_an_ide>`
  28. and :ref:`Compiling <toc-devel-compiling>` as the build tools are identical
  29. to the ones you need to compile Godot from source.
  30. You can download the `godot-cpp repository <https://github.com/godotengine/godot-cpp>`__ from GitHub or let Git do the work for you.
  31. Note that this repository has different branches for different versions
  32. of Godot. GDExtensions will not work in older versions of Godot (only Godot 4 and up) and vice versa, so make sure you download the correct branch.
  33. .. note::
  34. To use `GDExtension <https://godotengine.org/article/introducing-gd-extensions>`__
  35. you need to use the godot-cpp branch that matches the version of Godot that you are
  36. targeting. For example, if you're targeting Godot 4.1, use the ``4.1`` branch. Throughout
  37. this tutorial we use ``4.x``, which will need to be replaced with the version of Godot you
  38. are targeting.
  39. The ``master`` branch is the development branch which is updated regularly
  40. to work with Godot's ``master`` branch.
  41. .. warning::
  42. Our long-term goal is that GDExtensions targeting an earlier version of Godot will work
  43. in later minor versions, but not vice-versa. For example, a GDExtension targeting Godot 4.1
  44. should work just fine in Godot 4.2, but one targeting Godot 4.2 won't work in Godot 4.1.
  45. However, GDExtension is currently *experimental*, which means that we may break compatibility
  46. in order to fix major bugs or include critical features. For example, GDExtensions created
  47. for Godot 4.0 aren't compatible with Godot 4.1
  48. (see :ref:`updating_your_gdextension_for_godot_4_1`).
  49. If you are versioning your project using Git, it is recommended to add it as
  50. a Git submodule:
  51. .. code-block:: none
  52. mkdir gdextension_cpp_example
  53. cd gdextension_cpp_example
  54. git init
  55. git submodule add -b 4.x https://github.com/godotengine/godot-cpp
  56. cd godot-cpp
  57. git submodule update --init
  58. Alternatively, you can also clone it to the project folder:
  59. .. code-block:: none
  60. mkdir gdextension_cpp_example
  61. cd gdextension_cpp_example
  62. git clone -b 4.x https://github.com/godotengine/godot-cpp
  63. .. note::
  64. If you decide to download the repository or clone it into your folder,
  65. make sure to keep the folder layout the same as we've setup here. Much of
  66. the code we'll be showcasing here assumes the project has this layout.
  67. If you cloned the example from the link specified in the introduction, the
  68. submodules are not automatically initialized. You will need to execute the
  69. following commands:
  70. .. code-block:: none
  71. cd gdextension_cpp_example
  72. git submodule update --init
  73. This will initialize the repository in your project folder.
  74. Building the C++ bindings
  75. -------------------------
  76. Now that we've downloaded our prerequisites, it is time to build the C++
  77. bindings.
  78. The repository contains a copy of the metadata for the current Godot release,
  79. but if you need to build these bindings for a newer version of Godot, call
  80. the Godot executable:
  81. .. code-block:: none
  82. godot --dump-extension-api
  83. The resulting ``extension_api.json`` file will be created in the executable's
  84. directory. Copy it to the project folder and add ``custom_api_file=<PATH_TO_FILE>``
  85. to the scons command below.
  86. To generate and compile the bindings, use this command (replacing ``<platform>``
  87. with ``windows``, ``linux`` or ``macos`` depending on your OS):
  88. The build process automatically detects the number of CPU threads to use for
  89. parallel builds. To specify a number of CPU threads to use, add ``-jN`` at the
  90. end of the SCons command line where ``N`` is the number of CPU threads to use.
  91. .. code-block:: none
  92. cd godot-cpp
  93. scons platform=<platform> custom_api_file=<PATH_TO_FILE>
  94. cd ..
  95. This step will take a while. When it is completed, you should have static
  96. libraries that can be compiled into your project stored in ``godot-cpp/bin/``.
  97. .. note::
  98. You may need to add ``bits=64`` to the command on Windows or Linux.
  99. Creating a simple plugin
  100. ------------------------
  101. Now it's time to build an actual plugin. We'll start by creating an empty Godot
  102. project in which we'll place a few files.
  103. Open Godot and create a new project. For this example, we will place it in a
  104. folder called ``demo`` inside our GDExtension's folder structure.
  105. In our demo project, we'll create a scene containing a Node called "Main" and
  106. we'll save it as ``main.tscn``. We'll come back to that later.
  107. Back in the top-level GDExtension module folder, we're also going to create a
  108. subfolder called ``src`` in which we'll place our source files.
  109. You should now have ``demo``, ``godot-cpp``, and ``src``
  110. directories in your GDExtension module.
  111. Your folder structure should now look like this:
  112. .. code-block:: none
  113. gdextension_cpp_example/
  114. |
  115. +--demo/ # game example/demo to test the extension
  116. |
  117. +--godot-cpp/ # C++ bindings
  118. |
  119. +--src/ # source code of the extension we are building
  120. In the ``src`` folder, we'll start with creating our header file for the
  121. GDExtension node we'll be creating. We will name it ``gdexample.h``:
  122. .. code-block:: cpp
  123. :caption: gdextension_cpp_example/src/gdexample.h
  124. #pragma once
  125. #include <godot_cpp/classes/sprite2d.hpp>
  126. namespace godot {
  127. class GDExample : public Sprite2D {
  128. GDCLASS(GDExample, Sprite2D)
  129. private:
  130. double time_passed;
  131. protected:
  132. static void _bind_methods();
  133. public:
  134. GDExample();
  135. ~GDExample();
  136. void _process(double delta) override;
  137. };
  138. } // namespace godot
  139. There are a few things of note to the above. We include ``sprite2d.hpp`` which
  140. contains bindings to the Sprite2D class. We'll be extending this class in our
  141. module.
  142. We're using the namespace ``godot``, since everything in GDExtension is defined
  143. within this namespace.
  144. Then we have our class definition, which inherits from our Sprite2D through a
  145. container class. We'll see a few side effects of this later on. The
  146. ``GDCLASS`` macro sets up a few internal things for us.
  147. After that, we declare a single member variable called ``time_passed``.
  148. In the next block we're defining our methods, we have our constructor
  149. and destructor defined, but there are two other functions that will likely look
  150. familiar to some, and one new method.
  151. The first is ``_bind_methods``, which is a static function that Godot will
  152. call to find out which methods can be called and which properties it exposes.
  153. The second is our ``_process`` function, which will work exactly the same
  154. as the ``_process`` function you're used to in GDScript.
  155. Let's implement our functions by creating our ``gdexample.cpp`` file:
  156. .. code-block:: cpp
  157. :caption: gdextension_cpp_example/src/gdexample.cpp
  158. #include "gdexample.h"
  159. #include <godot_cpp/core/class_db.hpp>
  160. using namespace godot;
  161. void GDExample::_bind_methods() {
  162. }
  163. GDExample::GDExample() {
  164. // Initialize any variables here.
  165. time_passed = 0.0;
  166. }
  167. GDExample::~GDExample() {
  168. // Add your cleanup here.
  169. }
  170. void GDExample::_process(double delta) {
  171. time_passed += delta;
  172. Vector2 new_position = Vector2(10.0 + (10.0 * sin(time_passed * 2.0)), 10.0 + (10.0 * cos(time_passed * 1.5)));
  173. set_position(new_position);
  174. }
  175. This one should be straightforward. We're implementing each method of our class
  176. that we defined in our header file.
  177. Note our ``_process`` function, which keeps track of how much time has passed
  178. and calculates a new position for our sprite using a sine and cosine function.
  179. There is one more C++ file we need; we'll name it ``register_types.cpp``. Our
  180. GDExtension plugin can contain multiple classes, each with their own header
  181. and source file like we've implemented ``GDExample`` up above. What we need now
  182. is a small bit of code that tells Godot about all the classes in our
  183. GDExtension plugin.
  184. .. code-block:: cpp
  185. :caption: gdextension_cpp_example/src/register_types.cpp
  186. #include "register_types.h"
  187. #include "gdexample.h"
  188. #include <gdextension_interface.h>
  189. #include <godot_cpp/core/defs.hpp>
  190. #include <godot_cpp/godot.hpp>
  191. using namespace godot;
  192. void initialize_example_module(ModuleInitializationLevel p_level) {
  193. if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
  194. return;
  195. }
  196. GDREGISTER_RUNTIME_CLASS(GDExample);
  197. }
  198. void uninitialize_example_module(ModuleInitializationLevel p_level) {
  199. if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
  200. return;
  201. }
  202. }
  203. extern "C" {
  204. // Initialization.
  205. GDExtensionBool GDE_EXPORT example_library_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, const GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization) {
  206. godot::GDExtensionBinding::InitObject init_obj(p_get_proc_address, p_library, r_initialization);
  207. init_obj.register_initializer(initialize_example_module);
  208. init_obj.register_terminator(uninitialize_example_module);
  209. init_obj.set_minimum_library_initialization_level(MODULE_INITIALIZATION_LEVEL_SCENE);
  210. return init_obj.init();
  211. }
  212. }
  213. The ``initialize_example_module`` and ``uninitialize_example_module`` functions get
  214. called respectively when Godot loads our plugin and when it unloads it. All
  215. we're doing here is parse through the functions in our bindings module to
  216. initialize them, but you might have to set up more things depending on your
  217. needs. We call the ``GDREGISTER_RUNTIME_CLASS`` macro for each of our classes
  218. in our library. This will make them run only in game, like the default for GDScript.
  219. The important function is the third function called ``example_library_init``.
  220. We first call a function in our bindings library that creates an initialization object.
  221. This object registers the initialization and termination functions of the GDExtension.
  222. Furthermore, it sets the level of initialization (core, servers, scene, editor, level).
  223. At last, we need the header file for the ``register_types.cpp`` named
  224. ``register_types.h``.
  225. .. code-block:: cpp
  226. :caption: gdextension_cpp_example/src/register_types.h
  227. #pragma once
  228. #include <godot_cpp/core/class_db.hpp>
  229. using namespace godot;
  230. void initialize_example_module(ModuleInitializationLevel p_level);
  231. void uninitialize_example_module(ModuleInitializationLevel p_level);
  232. Compiling the plugin
  233. --------------------
  234. To compile the project we need to define how SCons using should compile it
  235. using a ``SConstruct`` file which references the one in ``godot-cpp``.
  236. Writing it from scratch is outside the scope of this tutorial, but you can
  237. :download:`the SConstruct file we prepared <files/cpp_example/SConstruct>`.
  238. We'll cover a more customizable, detailed example on how to use these
  239. build files in a subsequent tutorial.
  240. .. note::
  241. This ``SConstruct`` file was written to be used with the latest ``godot-cpp``
  242. master, you may need to make small changes using it with older versions or
  243. refer to the ``SConstruct`` file in the Godot 4.x documentation.
  244. Once you've downloaded the ``SConstruct`` file, place it in your GDExtension folder
  245. structure alongside ``godot-cpp``, ``src`` and ``demo``, then run:
  246. .. code-block:: bash
  247. scons platform=<platform>
  248. You should now be able to find the module in ``demo/bin/<platform>``.
  249. When building for iOS, package the module as a static `.xcframework`, you can use
  250. following commands to do so:
  251. ::
  252. # compile simulator and device modules
  253. scons arch=universal ios_simulator=yes platform=ios target=<target>
  254. scons arch=arm64 ios_simulator=no platform=ios target=<target>
  255. # assemble xcframeworks
  256. xcodebuild -create-xcframework -library demo/bin/libgdexample.ios.<target>.a -library demo/bin/libgdexample.ios.<target>.simulator.a -output demo/bin/libgdexample.ios.<target>.xcframework
  257. xcodebuild -create-xcframework -library godot-cpp/bin/libgodot-cpp.ios.<target>.arm64.a -library godot-cpp/bin/libgodot-cpp.ios.<target>.universal.simulator.a -output demo/bin/libgodot-cpp.ios.<target>.xcframework
  258. .. note::
  259. Here, we've compiled both godot-cpp and our gdexample library as debug
  260. builds. For optimized builds, you should compile them using the
  261. ``target=template_release`` switch.
  262. Using the GDExtension module
  263. ----------------------------
  264. Before we jump back into Godot, we need to create one more file in
  265. ``demo/bin/``.
  266. This file lets Godot know what dynamic libraries should be
  267. loaded for each platform and the entry function for the module. It is called ``gdexample.gdextension``.
  268. .. code-block:: none
  269. [configuration]
  270. entry_symbol = "example_library_init"
  271. compatibility_minimum = "4.1"
  272. reloadable = true
  273. [libraries]
  274. macos.debug = "res://bin/libgdexample.macos.template_debug.framework"
  275. macos.release = "res://bin/libgdexample.macos.template_release.framework"
  276. ios.debug = "res://bin/libgdexample.ios.template_debug.xcframework"
  277. ios.release = "res://bin/libgdexample.ios.template_release.xcframework"
  278. windows.debug.x86_32 = "res://bin/libgdexample.windows.template_debug.x86_32.dll"
  279. windows.release.x86_32 = "res://bin/libgdexample.windows.template_release.x86_32.dll"
  280. windows.debug.x86_64 = "res://bin/libgdexample.windows.template_debug.x86_64.dll"
  281. windows.release.x86_64 = "res://bin/libgdexample.windows.template_release.x86_64.dll"
  282. linux.debug.x86_64 = "res://bin/libgdexample.linux.template_debug.x86_64.so"
  283. linux.release.x86_64 = "res://bin/libgdexample.linux.template_release.x86_64.so"
  284. linux.debug.arm64 = "res://bin/libgdexample.linux.template_debug.arm64.so"
  285. linux.release.arm64 = "res://bin/libgdexample.linux.template_release.arm64.so"
  286. linux.debug.rv64 = "res://bin/libgdexample.linux.template_debug.rv64.so"
  287. linux.release.rv64 = "res://bin/libgdexample.linux.template_release.rv64.so"
  288. android.debug.x86_64 = "res://bin/libgdexample.android.template_debug.x86_64.so"
  289. android.release.x86_64 = "res://bin/libgdexample.android.template_release.x86_64.so"
  290. android.debug.arm64 = "res://bin/libgdexample.android.template_debug.arm64.so"
  291. android.release.arm64 = "res://bin/libgdexample.android.template_release.arm64.so"
  292. [dependencies]
  293. ios.debug = {
  294. "res://bin/libgodot-cpp.ios.template_debug.xcframework": ""
  295. }
  296. ios.release = {
  297. "res://bin/libgodot-cpp.ios.template_release.xcframework": ""
  298. }
  299. This file contains a ``configuration`` section that controls the entry function of the module.
  300. You should also set the minimum compatible Godot version with ``compatibility_minimum``,
  301. which prevents older version of Godot from trying to load your extension.
  302. The ``reloadable`` flag enables automatic reloading of your extension by the editor every time you recompile it,
  303. without needing to restart the editor. This only works if you compile your extension in debug mode (default).
  304. The ``libraries`` section is the important bit: it tells Godot the location of the
  305. dynamic library in the project's filesystem for each supported platform. It will
  306. also result in *just* that file being exported when you export the project,
  307. which means the data pack won't contain libraries that are incompatible with the
  308. target platform.
  309. Finally, the ``dependencies`` section allows you to name additional dynamic
  310. libraries that should be included as well. This is important when your GDExtension
  311. plugin implements someone else's library and requires you to supply a
  312. third-party dynamic library with your project.
  313. Here is another overview to check the correct file structure:
  314. .. code-block:: none
  315. gdextension_cpp_example/
  316. |
  317. +--demo/ # game example/demo to test the extension
  318. | |
  319. | +--main.tscn
  320. | |
  321. | +--bin/
  322. | |
  323. | +--gdexample.gdextension
  324. |
  325. +--godot-cpp/ # C++ bindings
  326. |
  327. +--src/ # source code of the extension we are building
  328. | |
  329. | +--register_types.cpp
  330. | +--register_types.h
  331. | +--gdexample.cpp
  332. | +--gdexample.h
  333. Time to jump back into Godot. We load up the main scene we created way back in
  334. the beginning and now add a newly available GDExample node to the scene:
  335. .. image:: img/gdextension_cpp_nodes.webp
  336. We're going to assign the Godot logo to this node as our texture, disable the
  337. ``centered`` property:
  338. .. image:: img/gdextension_cpp_sprite.webp
  339. We're finally ready to run the project:
  340. .. video:: img/gdextension_cpp_animated.webm
  341. :alt: Screen recording of a game window, with Godot logo moving in the top-left corner
  342. :autoplay:
  343. :loop:
  344. :muted:
  345. :align: default
  346. Adding properties
  347. -----------------
  348. GDScript allows you to add properties to your script using the ``export``
  349. keyword. In GDExtension you have to register the properties with a getter and
  350. setter function or directly implement the ``_get_property_list``, ``_get`` and
  351. ``_set`` methods of an object (but that goes far beyond the scope of this
  352. tutorial).
  353. Lets add a property that allows us to control the amplitude of our wave.
  354. In our ``gdexample.h`` file we need to add a member variable and getter and setter
  355. functions:
  356. .. code-block:: cpp
  357. ...
  358. private:
  359. double time_passed;
  360. double amplitude;
  361. public:
  362. void set_amplitude(const double p_amplitude);
  363. double get_amplitude() const;
  364. ...
  365. In our ``gdexample.cpp`` file we need to make a number of changes, we will only
  366. show the methods we end up changing, don't remove the lines we're omitting:
  367. .. code-block:: cpp
  368. void GDExample::_bind_methods() {
  369. ClassDB::bind_method(D_METHOD("get_amplitude"), &GDExample::get_amplitude);
  370. ClassDB::bind_method(D_METHOD("set_amplitude", "p_amplitude"), &GDExample::set_amplitude);
  371. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "amplitude"), "set_amplitude", "get_amplitude");
  372. }
  373. GDExample::GDExample() {
  374. // Initialize any variables here.
  375. time_passed = 0.0;
  376. amplitude = 10.0;
  377. }
  378. void GDExample::_process(double delta) {
  379. time_passed += delta;
  380. Vector2 new_position = Vector2(
  381. amplitude + (amplitude * sin(time_passed * 2.0)),
  382. amplitude + (amplitude * cos(time_passed * 1.5))
  383. );
  384. set_position(new_position);
  385. }
  386. void GDExample::set_amplitude(const double p_amplitude) {
  387. amplitude = p_amplitude;
  388. }
  389. double GDExample::get_amplitude() const {
  390. return amplitude;
  391. }
  392. Once you compile the module with these changes in place, you will see that a
  393. property has been added to our interface. You can now change this property and
  394. when you run your project, you will see that our Godot icon travels along a
  395. larger figure.
  396. Let's do the same but for the speed of our animation and use a setter and getter
  397. function. Our ``gdexample.h`` header file again only needs a few more lines of
  398. code:
  399. .. code-block:: cpp
  400. ...
  401. double amplitude;
  402. double speed;
  403. ...
  404. void _process(double delta) override;
  405. void set_speed(const double p_speed);
  406. double get_speed() const;
  407. ...
  408. This requires a few more changes to our ``gdexample.cpp`` file, again we're only
  409. showing the methods that have changed so don't remove anything we're omitting:
  410. .. code-block:: cpp
  411. void GDExample::_bind_methods() {
  412. ...
  413. ClassDB::bind_method(D_METHOD("get_speed"), &GDExample::get_speed);
  414. ClassDB::bind_method(D_METHOD("set_speed", "p_speed"), &GDExample::set_speed);
  415. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_speed", "get_speed");
  416. }
  417. GDExample::GDExample() {
  418. time_passed = 0.0;
  419. amplitude = 10.0;
  420. speed = 1.0;
  421. }
  422. void GDExample::_process(double delta) {
  423. time_passed += speed * delta;
  424. Vector2 new_position = Vector2(
  425. amplitude + (amplitude * sin(time_passed * 2.0)),
  426. amplitude + (amplitude * cos(time_passed * 1.5))
  427. );
  428. set_position(new_position);
  429. }
  430. ...
  431. void GDExample::set_speed(const double p_speed) {
  432. speed = p_speed;
  433. }
  434. double GDExample::get_speed() const {
  435. return speed;
  436. }
  437. Now when the project is compiled, we'll see another property called speed.
  438. Changing its value will make the animation go faster or slower.
  439. Furthermore, we added a property range which describes in which range the value can be.
  440. The first two arguments are the minimum and maximum value and the third is the step size.
  441. .. note::
  442. For simplicity, we've only used the hint_range of the property method.
  443. There are a lot more options to choose from. These can be used to
  444. further configure how properties are displayed and set on the Godot side.
  445. Signals
  446. -------
  447. Last but not least, signals fully work in GDExtension as well. Having your extension
  448. react to a signal given out by another object requires you to call ``connect``
  449. on that object. We can't think of a good example for our wobbling Godot icon, we
  450. would need to showcase a far more complete example.
  451. This is the required syntax:
  452. .. code-block:: cpp
  453. some_other_node->connect("the_signal", Callable(this, "my_method"));
  454. To connect our signal ``the_signal`` from some other node with our method
  455. ``my_method``, we need to provide the ``connect`` method with the name of the signal
  456. and a ``Callable``. The ``Callable`` holds information about an object on which a method
  457. can be called. In our case, it associates our current object instance ``this`` with the
  458. method ``my_method`` of the object. Then the ``connect`` method will add this to the
  459. observers of ``the_signal``. Whenever ``the_signal`` is now emitted, Godot knows which
  460. method of which object it needs to call.
  461. Note that you can only call ``my_method`` if you've previously registered it in
  462. your ``_bind_methods`` method. Otherwise Godot will not know about the existence
  463. of ``my_method``.
  464. To learn more about ``Callable``, check out the class reference here: :ref:`Callable <class_Callable>`.
  465. Having your object sending out signals is more common. For our wobbling
  466. Godot icon, we'll do something silly just to show how it works. We're going to
  467. emit a signal every time a second has passed and pass the new location along.
  468. In our ``gdexample.h`` header file, we need to define a new member ``time_emit``:
  469. .. code-block:: cpp
  470. ...
  471. double time_passed;
  472. double time_emit;
  473. double amplitude;
  474. ...
  475. This time, the changes in ``gdexample.cpp`` are more elaborate. First,
  476. you'll need to set ``time_emit = 0.0;`` in either our ``_init`` method or in our
  477. constructor. We'll look at the other 2 needed changes one by one.
  478. In our ``_bind_methods`` method, we need to declare our signal. This is done
  479. as follows:
  480. .. code-block:: cpp
  481. void GDExample::_bind_methods() {
  482. ...
  483. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_speed", "get_speed");
  484. ADD_SIGNAL(MethodInfo("position_changed", PropertyInfo(Variant::OBJECT, "node"), PropertyInfo(Variant::VECTOR2, "new_pos")));
  485. }
  486. Here, our ``ADD_SIGNAL`` macro can be a single call with a ``MethodInfo`` argument.
  487. ``MethodInfo``'s first parameter will be the signal's name, and its remaining parameters
  488. are ``PropertyInfo`` types which describe the essentials of each of the method's parameters.
  489. ``PropertyInfo`` parameters are defined with the data type of the parameter, and then the name
  490. that the parameter will have by default.
  491. So here, we add a signal, with a ``MethodInfo`` which names the signal "position_changed". The
  492. ``PropertyInfo`` parameters describe two essential arguments, one of type ``Object``, the other
  493. of type ``Vector2``, respectively named "node" and "new_pos".
  494. Next, we'll need to change our ``_process`` method:
  495. .. code-block:: cpp
  496. void GDExample::_process(double delta) {
  497. time_passed += speed * delta;
  498. Vector2 new_position = Vector2(
  499. amplitude + (amplitude * sin(time_passed * 2.0)),
  500. amplitude + (amplitude * cos(time_passed * 1.5))
  501. );
  502. set_position(new_position);
  503. time_emit += delta;
  504. if (time_emit > 1.0) {
  505. emit_signal("position_changed", this, new_position);
  506. time_emit = 0.0;
  507. }
  508. }
  509. After a second has passed, we emit our signal and reset our counter. We can add
  510. our parameter values directly to ``emit_signal``.
  511. Once the GDExtension library is compiled, we can go into Godot and select our sprite
  512. node. In the **Node** dock, we can find our new signal and link it up by pressing
  513. the **Connect** button or double-clicking the signal. We've added a script on
  514. our main node and implemented our signal like this:
  515. .. code-block:: gdscript
  516. extends Node
  517. func _on_Sprite2D_position_changed(node, new_pos):
  518. print("The position of " + node.get_class() + " is now " + str(new_pos))
  519. Every second, we output our position to the console.
  520. Next steps
  521. ----------
  522. We hope the above example showed you the basics. You can build upon this example to create full-fledged scripts
  523. to control nodes in Godot using C++!
  524. Instead of basing your project off the above example setup, we recommend to restart now by cloning the
  525. `godot-cpp template <https://github.com/godotengine/godot-cpp-template>`__, and base your project off of that.
  526. It has better coverage of features, such as a GitHub build action and additional useful ``SConstruct`` boilerplate.