gdextension_cpp_example.rst 26 KB

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