### Install GitBook Plugins Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/README.md Installs the necessary GitBook plugins for the documentation project. This command should be run within the project directory. ```bash gitbook install ``` -------------------------------- ### Install Android SDK and NDK using Brew Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-terminal.md Use this command to install the Android SDK and NDK via the brew package manager. This simplifies the installation process. ```sh $ brew tap caskroom/cask $ brew cask install android-sdk android-ndk ``` -------------------------------- ### Install GitBook CLI Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/README.md Installs the GitBook command-line interface globally. This is a prerequisite for building and serving the documentation. ```bash npm install gitbook-cli -g ``` -------------------------------- ### Create a new Scene Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/scenes/transitioning.md This is a basic scene creation example. ```cpp auto myScene = Scene::create(); ``` -------------------------------- ### Install Python for Ubuntu Versions Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Linux.md Installs the appropriate Python version for different Ubuntu releases. Use this command before proceeding with other setup steps. ```sh sudo apt-get install python2 ``` ```sh sudo apt-get install python2.7 ``` ```sh sudo apt-get install python-minimal ``` -------------------------------- ### Clone Repo and Setup Dependencies Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Linux.md Installs Git, clones the Cocos2d-x repository, updates submodules, and downloads necessary dependencies. Ensure you are in the desired directory before cloning. ```sh sudo apt-get install git cd git clone https://github.com/cocos2d/cocos2d-x.git cd cocos2d-x-root #where your cocos2d-x directory is located. git submodule update --init git submodule update ./download-deps.py ``` -------------------------------- ### Get Director Instance and Run Scene Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/basic_concepts/director.md Obtain the Director singleton instance and start the game with an initial scene. This is typically used at the beginning of the game. ```cpp auto director = cocos2d::Director::getInstance(); director->runWithScene(scene); ``` -------------------------------- ### Run Cocos2d-x Setup Script Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-VisualStudio.md Execute the setup script from the Cocos2d-x directory to configure your environment. Ensure Python is in your PATH. ```sh python setup.py ``` -------------------------------- ### Setup Cocos2d-x Environment Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/editors_and_tools/cocosCLTool.md Run the setup script to configure your system's PATH for Cocos2d-x tools. This ensures that commands like 'cocos' can be executed from any directory. ```sh # Option 1 > ./setup.py # Option 2 > python setup.py ``` -------------------------------- ### Build and Install Android Test App Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/release_notes/cocos2d-x/v3.11.1.md Build the cpp-empty-test for Android using the android-build.py script and install the debug APK onto a device. ```bash cd cocos2d-x ./setup.py cd build ./android-build.py cpp-empty-test -p 10 adb install cocos2d-x/tests/cpp-empty-test/proj.android/bin/CppEmptyTest-debug.apk ``` -------------------------------- ### Start Game with runWithScene Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/scenes/transitioning.md Use this method to launch the very first scene of your game. It initializes the director with the specified scene. ```cpp Director::getInstance()->runWithScene(myScene); ``` -------------------------------- ### Build and Run Linux Tests Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/release_notes/cocos2d-x/v3.11.1.md Install dependencies, configure the build with CMake, compile the project, and run the cpp-empty-test executable on Linux. ```bash cd cocos2d-x/build ./install-deps-linux.sh cd ../.. mkdir build cd build cmake ../cocos2d-x make -j4 cd bin/cpp-empty-test ./cpp-empty-test ``` -------------------------------- ### Clone Cocos2d-x Repository and Setup Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/about/how.md Steps to clone the cocos2d-x develop branch, checkout a specific version, and download dependencies. This is the initial setup for contributing code. ```shell $ git clone git://github.com/cocos2d/cocos2d-x.git $ cd cocos2d-x $ git checkout v3 $ ./download-deps.py $ git submodule update --init ``` -------------------------------- ### Verify Java Installation Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-terminal.md Test if the Java Development Kit (JDK) is correctly installed and accessible by checking its version. This confirms that JAVA_HOME is set properly. ```sh > java -v ``` -------------------------------- ### Build and Install C++ Empty Test on Android Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/release_notes/cocos2d-x/v3.11.md Build the C++ empty test project for Android using the android-build.py script and install the resulting APK onto a device. Supports API levels from 10 upwards. ```bash cd cocos2d-x ./setup.py cd build ./android-build.py cpp-empty-test -p 10 adb install cocos2d-x/tests/cpp-empty-test/proj.android/bin/CppEmptyTest-debug.apk ``` -------------------------------- ### Simple Lambda Function Example Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/ui_components/menus.md Demonstrates the creation and invocation of a simple C++ lambda function. ```cpp // create a simple Hello World lambda auto func = [] () { cout << "Hello World"; }; // now call it someplace in code func(); ``` -------------------------------- ### Install Android App using ADB Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-terminal.md Use this command to install the generated .apk file onto your connected Android device via ADB. Ensure USB debugging is enabled on your phone and you are in the 'bin' directory of your Android project. ```sh > adb install MyGame-debug.apk ``` -------------------------------- ### Clone Cocos2d-x Repository and Setup Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/OSX.md Use these commands to clone the Cocos2d-x GitHub repository and initialize submodules. This is an alternative to downloading a zip archive. ```shell cd git clone git@github.com:cocos2d/cocos2d-x.git cd cocos2d-x git submodule update --init ./download-deps.py ``` -------------------------------- ### Creating and Sending an HTTP GET Request Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/advanced_topics/networking.md This snippet demonstrates how to create an HttpRequest object, set its URL and request type (GET), and send it using the HttpClient. A response callback is also specified to handle the server's reply. ```cpp HttpRequest* request = new ( std :: nothrow) HttpRequest(); request->setUrl("//just-make-this-request-failed.com"); request->setRequestType(HttpRequest::Type::GET); request->setResponseCallback(CC_CALLBACK_2 (HttpClientTest::onHttpRequestCompleted, this)); HttpClient::getInstance()->sendImmediate(request); request->release(); ``` -------------------------------- ### Deploy Cocos Project to Win32 (Release Mode) Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/editors_and_tools/cocos.md Example of deploying a Cocos project to the Win32 platform in release mode. Use forward or backward slashes for the path. ```bash cocos deploy -s c:\MyCompany\MyGame -p win32 -m release ``` -------------------------------- ### Create and Run Initial Scene Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/basic_concepts/getting_started.md This code snippet from AppDelegate::applicationDidFinishLaunching() shows how to create the first scene of your game and run it using the director. ```cpp // create a scene. it's an autorelease object auto scene = HelloWorld::createScene(); // run director->runWithScene(scene); ``` -------------------------------- ### Verify Python Version Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-terminal.md Check if Python is installed and if its version is less than 3. This is a critical step before proceeding with the Android setup. ```sh > python --version ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/README.md Builds and serves the documentation site locally with live reloading. This command is used for previewing changes as you make them. ```bash gitbook serve ``` -------------------------------- ### Initialize and Connect to Database Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/tutorials/storing-game-data/index.md Initializes the database instance, attempts to connect, and checks if the database is already populated. Use this to manage game data persistence. ```cpp void SQLManager::initInstance() { if (connect()) { if (isDatabasePopulated()) { // the database was found and is populated. } else { // a new database was created, so we need to pupulate it. } } else { // we failed to connect, handle this more gracefully for production!!! std::cout << "We cannot connect to database" << std::endl; } } bool SQLManager::connect() { bool _bConnect = false; _pdb = NULL; _dbPath = cocos2d::FileUtils::getInstance()->getWritablePath() + _dbFile; int result = sqlite3_open(_dbPath.c_str(), &_pdb); if(result == SQLITE_OK) { //std::cout << "open database successfull!" _bConnect = true; } return _bConnect; } bool SQLManager::isDatabasePopulated() { // check to see if the database is populated, this means it already existed. // If it isn't populated we need to populate it with initial values } ``` -------------------------------- ### Common AABB Functions Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/3d/terminology.md Provides examples of commonly used functions for AABB manipulation and detection, including getting corners, point containment, merging boxes, updating bounds, and transformation. ```cpp void getCorners (Vec3 * dst) const; // get the world coordinate AABB 8 vertices bool containPoint (const Vec3 & point) const; // detect whether a point is contained in a box inside the AABB void merge (const AABB & box); // merge two AABB box void updateMinMax (const Vec3 * point, ssize_t num); // update Pmin or Pmax void transform (const Mat4 & mat); // transform operation on the AABB Box ``` -------------------------------- ### Get Tile ID from Layer Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/other_node_types/tilemap.md This example illustrates how to obtain the unique ID (GID) of a specific tile at a given position within a TileMap layer. This ID can be used for various game logic. ```cpp // to obtain a specific tiles id unsigned int gid = layer->getTileGIDAt(Vec2(0, 63)); ``` -------------------------------- ### Control Particle System Lifecycle Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/3d/advanced.md Manage the state of a ParticleSystem3D using these methods. They allow you to start, stop, pause, and resume particle emission, as well as get the current count of active particles. ```cpp virtual void startParticleSystem() override; virtual void stopParticleSystem() override; virtual void pauseParticleSystem() override; virtual void resumeParticleSystem() override; virtual int getAliveParticleCount() const override; ``` -------------------------------- ### Run Tizen Project on Simulator Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Tizen.md Launch the Tizen simulator and run your project on it using this command. Remember that the Tizen simulator must be running for this command to work. Specify the project path, Tizen platform, profile path, and sign string. ```bash cocos run -s PROJECT_PATH -p tizen --tizen-profile PROFILE_PATH --tizen-sign SIGN_STRING ``` -------------------------------- ### Set Environment Variables for Manual Installation Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-terminal.md If installing the Android NDK and SDK manually, set these environment variables using your custom installation paths. Ensure these paths accurately reflect where you downloaded the SDK and NDK. ```sh export NDK_ROOT=/Users/username/Projects/android-ndk/r12b export PATH=$NDK_ROOT:$PATH export ANDROID_HOME=/Users/username/Projects/android-sdk export ANDROID_SDK_ROOT=/Users/username/Projects/android-sdk/24.4.1_1 export PATH=$ANDROID_SDK_ROOT:$PATH export PATH=$ANDROID_SDK_ROOT/tools:$ANDROID_SDK_ROOT/platform-tools:$PATH ``` -------------------------------- ### Create and Configure LoadingBar Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/ui_components/loading_bar.md Demonstrates how to create a LoadingBar instance and set its fill direction. This is useful for initializing the progress bar's appearance. ```cpp #include "ui/CocosGUI.h" auto loadingBar = LoadingBar::create("LoadingBarFile.png"); // set the direction of the loading bars progress loadingBar->setDirection(LoadingBar::Direction::RIGHT); this->addChild(loadingBar); ``` -------------------------------- ### Create a Sequence of Actions Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/basic_concepts/sequences.md Use Sequence::create to run multiple actions in a defined order. This example demonstrates moving a sprite to specific points, with delays and relative movements. ```cpp auto mySprite = Node::create(); // move to point 50,10 over 2 seconds auto moveTo1 = MoveTo::create(2, Vec2(50,10)); // move from current position by 100,10 over 2 seconds auto moveBy1 = MoveBy::create(2, Vec2(100,10)); // move to point 150,10 over 2 seconds auto moveTo2 = MoveTo::create(2, Vec2(150,10)); // create a delay auto delay = DelayTime::create(1); mySprite->runAction(Sequence::create(moveTo1, delay, moveBy1, delay.clone(), moveTo2, nullptr)); ``` -------------------------------- ### Setting up Mouse Event Listener Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/event_dispatcher/mouse.md Create and configure a mouse event listener to capture mouse events like movement, clicks, and scrolling. Attach the listener to the event dispatcher. ```cpp _mouseListener = EventListenerMouse::create(); _mouseListener->onMouseMove = CC_CALLBACK_1(MouseTest::onMouseMove, this); _mouseListener->onMouseUp = CC_CALLBACK_1(MouseTest::onMouseUp, this); _mouseListener->onMouseDown = CC_CALLBACK_1(MouseTest::onMouseDown, this); _mouseListener->onMouseScroll = CC_CALLBACK_1(MouseTest::onMouseScroll, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); ``` -------------------------------- ### Update and Upgrade System Packages Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Linux.md Updates the package list and upgrades installed packages on your system. This is a standard maintenance step before installing new software. ```sh sudo apt-get update sudo apt-get upgrade ``` -------------------------------- ### List Installed JDKs Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-terminal.md Display a list of all installed Java Development Kits (JDKs) on your macOS system. This command is useful for troubleshooting JAVA_HOME configuration issues. ```sh > usr/libexec/java_home -V ``` -------------------------------- ### Create and Use Subclass Instance Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/scripting/script_component.md Demonstrates how to create an instance of the `SubNode` class using its `new` method and call its custom `addSprite` method. ```lua local node = SubNode.new() node:addSprite("xxx.jpg") ``` -------------------------------- ### Install Cocos2d-x Dependencies for Ubuntu 16.x Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Linux.md Installs essential development libraries and tools required for Cocos2d-x on Ubuntu 16.x. This command should be run after updating your system. ```sh sudo apt-get install g++ libgdk-pixbuf2.0-dev python-pip cmake libx11-dev libxmu-dev libglu1-mesa-dev libgl2ps-dev libxi-dev libzip-dev libpng-dev libcurl4-gnutls-dev libfontconfig1-dev libsqlite3-dev libglew-dev libssl-dev libgtk-3-dev libglfw3 libglfw3-dev xorg-dev ``` -------------------------------- ### Create Sprite with FileUtils Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/advanced_topics/advanced_topics-img/file_system_access.md Demonstrates creating a Sprite by referencing a file directly from the Resources folder. ```c++ auto sprite = Sprite::create("picture.png"); ``` -------------------------------- ### Build Documentation HTML Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/README.md Builds only the HTML output for the documentation site. This command is used for generating the final static site files. ```bash gitbook build ``` -------------------------------- ### Create and Run a Sequence with Actions and Callbacks Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/actions/sequences.md Use Sequence.create to chain actions and CallFunc for custom logic. Ensure the sequence is terminated with nullptr. ```cpp auto mySprite = Sprite::create("mysprite.png"); // create a few actions. auto jump = JumpBy::create(0.5, Vec2(0, 0), 100, 1); auto rotate = RotateTo::create(2.0f, 10); // create a few callbacks auto callbackJump = CallFunc::create([](){ log("Jumped!"); }); auto callbackRotate = CallFunc::create([](){ log("Rotated!"); }); // create a sequence with the actions and callbacks auto seq = Sequence::create(jump, callbackJump, rotate, callbackRotate, nullptr); // run it mySprite->runAction(seq); ``` -------------------------------- ### Set Environment Variables for Brew Installation Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-terminal.md After installing with brew, set these environment variables in your .bash_profile to correctly locate the Android NDK and SDK. Remember to re-source your .bash_profile. ```sh export NDK_ROOT=/usr/local/Cellar/android-ndk/r12b export PATH=$NDK_ROOT:$PATH export ANDROID_HOME=/usr/local/opt/android-sdk export ANDROID_SDK_ROOT=/usr/local/Cellar/android-sdk/24.4.1_1 export PATH=$ANDROID_SDK_ROOT:$PATH export PATH=$ANDROID_SDK_ROOT/tools:$ANDROID_SDK_ROOT/platform-tools:$PATH ``` -------------------------------- ### Check Cocos CLI Installation Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/editors_and_tools/cocos.md Verify that the 'cocos' command-line tool is installed and accessible in your system's PATH. Successful execution displays the tool's version. ```bash cocos -v ``` -------------------------------- ### Define a Material with Techniques, Passes, and Shaders Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/advanced_topics/shaders.md This is an example of a `.material` file defining a material named 'spaceship' with a single technique 'normal'. It includes a pass with vertex and fragment shaders, uniforms, and sampler configurations. It also specifies render states like cull face and depth test. ```cpp // A "Material" file can contain one or more materials material spaceship { // A Material contains one or more Techniques. // In case more than one Technique is present, the first one will be the default one // A "Technique" describes how the material is going to be renderer // Techniques could: // - define the render quality of the model: high quality, low quality, etc. // - lit or unlit an object // etc... technique normal { // A technique can contain one or more passes // A "Pass" describes the "draws" that will be needed // in order to achieve the desired technique // The 3 properties of the Passes are shader, renderState and sampler pass 0 { // shader: responsible for the vertex and frag shaders, and its uniforms shader { vertexShader = Shaders3D/3d_position_tex.vert fragmentShader = Shaders3D/3d_color_tex.frag // uniforms, including samplers go here u_color = 0.9,0.8,0.7 // sampler: the id is the uniform name sampler u_sampler0 { path = Sprite3DTest/boss.png mipmap = true wrapS = CLAMP wrapT = CLAMP minFilter = NEAREST_MIPMAP_LINEAR magFilter = LINEAR } } // renderState: responsible for depth buffer, cullface, stencil, blending, etc. renderState { cullFace = true cullFaceSide = FRONT depthTest = true } } } } ``` -------------------------------- ### Run Cocos2d-x Web Project with Specific Browser (Windows) Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/editors_and_tools/cocos.md This example demonstrates launching Google Chrome on Windows for a web project build. Ensure the path to the executable is correct. ```bash cocos run -s ~/MyCompany/MyGame -p web -b C:\Program\ Files\Google\Chrome\Application\chrome.exe ``` -------------------------------- ### Add Repository for Ubuntu 17.x Dependencies Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Linux.md Adds a specific repository to your system's sources list to enable the installation of required dependencies on Ubuntu 17.x. This is a prerequisite for the next installation step. ```sh deb //cz.archive.ubuntu.com/ubuntu xenial main ``` -------------------------------- ### Basic Logging with log() Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/basic_concepts/logging.md Demonstrates various ways to use the `log()` function to output strings, integers, floats, doubles, and booleans to the console. Use appropriate format specifiers like %s, %d, %f. ```cpp // a simple string log("This would be outputted to the console"); // a string and a variable string s = "My variable"; log("string is %s", s); // a double and a variable double dd = 42; log("double is %f", dd); // an integer and a variable int i = 6; log("integer is %d", i); // a float and a variable float f = 2.0f; log("float is %f", f); // a bool and a variable bool b = true; if (b == true) log("bool is true"); else log("bool is false"); ``` -------------------------------- ### List Available Android SDK Targets Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/Android-terminal.md Before building, run this command to see a list of available Android SDK targets. You will need to specify one of these targets when building. ```sh > android list targets ``` -------------------------------- ### Create and Add Spot Light Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/3d/lighting.md SpotLight simulates a flashlight, emitting light in a cone shape. Add the created light to the scene graph. ```cpp auto spotLight = SpotLight::create(Vec3(-1.0f, -1.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Color3B::RED, 0.0, 0.5, 10000.0f) ; addChild(spotLight); ``` -------------------------------- ### Get Bodies from Contact Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/physics/collisions.md Retrieve the PhysicsBody objects associated with two colliding shapes from a PhysicsContact object. ```cpp bool onContactBegin(PhysicsContact& contact) { auto bodyA = contact.getShapeA()->getBody(); auto bodyB = contact.getShapeB()->getBody(); return true; } ``` -------------------------------- ### Correct Action Application with clone() Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/actions/sequence_internals.md Shows the correct way to apply an action to multiple nodes by using 'clone()' to ensure each node receives a unique action instance with its own internal state. ```cpp // create our Sprites auto heroSprite = Sprite::create("herosprite.png"); auto enemySprite = Sprite::create("enemysprite.png"); // create an Action auto moveBy = MoveBy::create(10, Vec2(400,100)); // run it on our hero heroSprite->runAction(moveBy); // run it on our enemy enemySprite->runAction(moveBy->clone()); // correct! This will be unique ``` -------------------------------- ### Stop Audio Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/audio/operations.md Provides examples for stopping background music, individual sound effects, or all sound effects. ```APIDOC ## Stop Audio ### Description Enables stopping background music, a specific sound effect, or all currently playing sound effects. ### Method C++ (SimpleAudioEngine) ### Usage ```cpp #include "SimpleAudioEngine.h" using namespace CocosDenshion; auto audio = SimpleAudioEngine::getInstance(); // stop background music. audio->stopBackgroundMusic(); // stop a sound effect. audio->stopEffect(); // stops all running sound effects. audio->stopAllEffects(); ``` ``` -------------------------------- ### Create ParticleSystem3D with PU and Material Files Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/3d/advanced.md Use this method to create a ParticleSystem3D by specifying both the Particle Universe (.pu) file and its corresponding material file. This is preferred when you know the exact material to use. ```cpp auto ps = PUParticleSystem3D::create("lineStreak.pu", "pu_mediapack_01.material"); ps->startParticleSystem(); this->addChild(ps); ``` -------------------------------- ### Check CMake Version Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/installation/CMake-Guide.md Verify that your installed CMake version meets the minimum requirement of 3.1. Execute this command in your terminal. ```sh cmake --version ``` -------------------------------- ### Accessing UserDefault Instance Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/tutorials/storing-game-data/index.md Get the singleton instance of UserDefault. It's recommended to store the instance in a variable for repeated access. ```cpp cocos2d::UserDefault::getInstance()->someFunction(); ``` ```cpp auto userdefaults = cocos2d::UserDefault::getInstance(); userdefaults->setStringForKey("message", "Hello"); userdefaults->setIntegerForKey("score", 10); ``` -------------------------------- ### Creating and Handling Keyboard Event Listeners Source: https://github.com/cocos2d/cocos2d-x-docs/blob/master/en/event_dispatcher/keyboard.md This snippet demonstrates how to create a keyboard event listener, assign callback functions for key press and release events, and add the listener to the event dispatcher. It also shows the implementation of the callback functions. ```cpp // creating a keyboard event listener auto listener = EventListenerKeyboard::create(); listener->onKeyPressed = CC_CALLBACK_2(KeyboardTest::onKeyPressed, this); listener->onKeyReleased = CC_CALLBACK_2(KeyboardTest::onKeyReleased, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // Implementation of the keyboard event callback function prototype void KeyboardTest::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event) { log("Key with keycode %d pressed", keyCode); } void KeyboardTest::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event) { log("Key with keycode %d released", keyCode); } ```