Cocos Example Projects

repository·master·Indexed 20 days ago

https://github.com/cocos/cocos-example-projects

A collection of specialized Cocos Creator example projects demonstrating engine features, native integrations, and third-party module usage. Key examples include the native-script-bridge for bidirectional JS-Native communication (Android, iOS, Windows, Mac), Physics 3D functional testing and demonstrations, protobuf.js implementation for encoding/decoding, and NPM module interoperability cases.

Tokens
6K
Snippets
16
Records
27
Agent score
69%

What's inside cocos-example-projects

  1. Overview of Cocos Creator Example Projects

    master
    This repository provides a collection of standalone Cocos Creator projects designed to demonstrate specific engine features and integration patterns. Each folder in the repository represents a separate, functional project that can be used as a reference or template for implementing similar functionality in your own Cocos Creator applications.
  2. Verify Native Plugin and Native Project Template Compatibility

    master
    This example project is used to test the compatibility of Native Project templates and the effectiveness of Native Plugins starting from Cocos Creator version 3.6.1. It serves as a validation tool to ensure that custom native code and plugin integrations function correctly within the Cocos environment.
  3. Use protobuf.js in Cocos Creator 3D

    master
    This project demonstrates how to implement Protocol Buffers (protobuf) encoding and decoding within a Cocos Creator 3D environment using the protobuf.js library. In the provided example, clicking a model triggers the encoding of a protobuf message sent to other models, which then decode and display the message.
  4. Use the native-script-bridge for JS-Native communication

    master

    The native-script-bridge provides a simplified mechanism for bidirectional communication between the JavaScript layer and the Native layer (Android/Java and iOS/Objective-C).

    Key Constraints

    • Data Type: Currently, only string data is supported. To transmit complex objects, serialize them into a JSON string in the sender layer and parse them in the receiver layer.
    • Callback Lifecycle: The onNative property in JavaScript can only hold one callback function at a time; setting it again will overwrite the previous handler.
    • Communication Model: sendToNative (JS to Native) is a one-way communication. It does not wait for a response or notify the JS layer of success or failure.
    // JavaScript API Surface
    export namespace bridge {
        /**
         * Send data to the native layer.
         * @param arg0 First string argument
         * @param arg1 Optional second string argument
         */
        export function sendToNative(arg0: string, arg1?: string): void;
    
        /**
         * Register a callback to receive data from the native layer.
         * Overwrites any existing callback.
         * @param args Received from native
         */
        export function onNative(arg0: string, arg1?: string | null): void;
    }
  5. Explore Cocos Creator 3D Physics 3D examples and tests

    master

    This project serves as a functional testing and demonstration suite for Physics 3D in Cocos Creator 3D. It is organized into several directories within the assets folder to help you find specific use cases or testing scenarios:

    • cases: Contains files used for functional testing.
    • demo: Contains case demonstrations showing how physics features work in practice.
    • experiment: Contains experimental physics features.
    • common: Contains common dynamic resources used across multiple cases.
    • resouces: Contains dynamic resources. Subfolders like simple-car/ contain resources specific to a single case, while common/ contains shared resources.
    • misc: Miscellaneous files.

    To run all tests and demonstrations at once, use the TestList.scene.

  6. What is JsbBridgeWrapper and when to use it

    master

    JsbBridgeWrapper is an event dispatch mechanism built on top of JsbBridge. It provides a more convenient and intuitive way to trigger multiple events without manually implementing a message sending/receiving mechanism.

    Warning: It is built upon existing example implementations and does not guarantee multi-threaded stability or 100% safety. For complex requirements or high-concurrency scenarios, it is recommended to implement a custom event dispatch system.

  7. Manage multiple Native-to-JS callbacks using a Method Manager

    master

    Because jsb.bridge.onNative and the native setCallback can only hold one reference at a time, you should use a MethodManager pattern to route different native calls to specific JavaScript functions.

    1. Create a MethodManager singleton to store a map of method names to functions.
    2. In your Cocos Creator component's start() method, assign a single handler to jsb.bridge.onNative that calls MethodManager.instance.applyMethod(methodName, arg).
    3. Register your specific logic functions with the manager using addMethod.
    export class MethodManager {
        private methodMap: Map<String, Function>;
        public static instance: MethodManager = new MethodManager;
    
        public addMethod(methodName: String, f: Function): boolean {
            if (!this.methodMap.get(methodName)) {
                this.methodMap.set(methodName, f);
                return true;
            }
            return false;
        }
    
        public applyMethod(methodName: String, arg?: String): boolean {
            const f = this.methodMap.get(methodName);
            if (!f) return false;
            try {
                f?.call(null, arg);
                return true;
            } catch (e) {
                return false;
            }
        }
    
        public removeMethod(methodName: String): any {
            return this.methodMap.delete(methodName);
        }
    
        constructor() {
            this.methodMap = new Map<String, Function>();
            MethodManager.instance = this;
        }
    }
    
    // Usage in a Component
    @ccclass('CallNative')
    export class CallNative extends Component {
        start() {
            new MethodManager();
            jsb.bridge.onNative = (methodName: string, arg1?: string | null) => {
                MethodManager.instance.applyMethod(methodName, arg1!);
            };
            
            // Register specific methods
            MethodManager.instance.addMethod("changeLabelContent", (usr: string) => {
                this.changeLabelContent(usr);
            });
        }
    
        public changeLabelContent(user: string): void {
            // Logic to update UI
        }
    }
  8. Project directory structure for protobuf integration

    master

    The following directory structure is used to manage the protobuf libraries and generated files:

    • assets/thirdy: Contains the core library files protobuf.js and long.js.
    • assets/proto/awesome.js: The generated JavaScript data definition file produced from protos/awesome.proto.
    • assets/proto/awesome.d.ts: The generated TypeScript declaration file.

    Note: The specific commands used to generate these files are located in tools/compile-proto/package.json.

  9. Install external NPM modules for the npm-case project

    master

    This project uses external NPM modules to demonstrate module interactions within Cocos Creator. When you first clone the project, update it via git, or clear temporary files, you must install the dependencies manually.

    Navigate to the /npm-case/ directory and run the following command:

    npm install --no-save

    Note: You do not need to manually clear the node_modules/ directory before running this command.

  10. Implement Native-to-JS callbacks in Android (Java)

    master

    To receive calls from JavaScript in Android, you must register a callback using JsbBridge.setCallback.

    1. Initialize your bridge logic in onCreate of your CocosActivity using a helper class (e.g., JsbBridgeTest.start()).
    2. Use a HashMap to map string keys to specific callback logic.
    3. In the JsbBridge.ICallback.onScript(String arg0, String arg1) implementation, retrieve the corresponding callback from your map and execute it.
    4. To send data back to JavaScript, use JsbBridge.sendToScript(methodName, argument).
    // In AppActivity.java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JsbBridgeTest.start();
    }
    
    // In JsbBridgeTest.java
    public class JsbBridgeTest {
        public interface MyCallback {
            void onTrigger(String arg);
        }
        public static HashMap<String, MyCallback> myCallbackHashMap = new HashMap<>();
    
        public static void start() {
            // Map a string key to a specific action that calls JS
            JsbBridgeTest.myCallbackHashMap.put("requestLabelContent", arg -> {
                JsbBridge.sendToScript("changeLabelContent", "Charlotte");
            });
    
            // Register the global bridge callback
            JsbBridge.setCallback(new JsbBridge.ICallback() {
                @Override
                public void onScript(String arg0, String arg1) {
                    JsbBridgeTest.myCallbackHashMap.get(arg0).onTrigger(arg1);
                }
            });
        }
    }
  11. Update proto files in Cocos Creator 3D

    master

    To update the generated JavaScript and TypeScript definitions from your .proto files, follow these steps:

    1. Initial Setup: If you haven't already, install the necessary dependencies in the compilation tool directory:

      cd tools/compile-proto
      npm install
    2. Rebuild Definitions: Every time you modify your .proto files, run the build script to regenerate the awesome.js and awesome.d.ts files:

      cd tools/compile-proto
      npm run build-proto
    cd tools/compile-proto
    npm run build-proto