Cocos Example Projects
repository·master·Indexed 20 days ago
https://github.com/cocos/cocos-example-projectsA 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.
What's inside cocos-example-projects
- 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.
Verify Native Plugin and Native Project Template Compatibility
masterThis 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.Use protobuf.js in Cocos Creator 3D
masterThis project demonstrates how to implement Protocol Buffers (protobuf) encoding and decoding within a Cocos Creator 3D environment using theprotobuf.jslibrary. 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.Use the native-script-bridge for JS-Native communication
masterThe
native-script-bridgeprovides 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
stringdata 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
onNativeproperty 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; }- Data Type: Currently, only
Explore Cocos Creator 3D Physics 3D examples and tests
masterThis project serves as a functional testing and demonstration suite for Physics 3D in Cocos Creator 3D. It is organized into several directories within the
assetsfolder 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 likesimple-car/contain resources specific to a single case, whilecommon/contains shared resources.misc: Miscellaneous files.
To run all tests and demonstrations at once, use the
TestList.scene.What is JsbBridgeWrapper and when to use it
masterJsbBridgeWrapperis an event dispatch mechanism built on top ofJsbBridge. 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.
Manage multiple Native-to-JS callbacks using a Method Manager
masterBecause
jsb.bridge.onNativeand the nativesetCallbackcan only hold one reference at a time, you should use aMethodManagerpattern to route different native calls to specific JavaScript functions.- Create a
MethodManagersingleton to store a map of method names to functions. - In your Cocos Creator component's
start()method, assign a single handler tojsb.bridge.onNativethat callsMethodManager.instance.applyMethod(methodName, arg). - 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 } }- Create a
Project directory structure for protobuf integration
masterThe following directory structure is used to manage the protobuf libraries and generated files:
assets/thirdy: Contains the core library filesprotobuf.jsandlong.js.assets/proto/awesome.js: The generated JavaScript data definition file produced fromprotos/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.Install external NPM modules for the npm-case project
masterThis 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-saveNote: You do not need to manually clear the
node_modules/directory before running this command.Implement Native-to-JS callbacks in Android (Java)
masterTo receive calls from JavaScript in Android, you must register a callback using
JsbBridge.setCallback.- Initialize your bridge logic in
onCreateof yourCocosActivityusing a helper class (e.g.,JsbBridgeTest.start()). - Use a
HashMapto map string keys to specific callback logic. - In the
JsbBridge.ICallback.onScript(String arg0, String arg1)implementation, retrieve the corresponding callback from your map and execute it. - 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); } }); } }- Initialize your bridge logic in
Configure Environment for Native Plugin Testing
masterTo run this example project, ensure your development environment meets the following requirements based on your target platform:
Windows
- Visual Studio: Requires VS2019.
Android
- Android Studio: Must have CMake 3.18.1+ installed via the Android Studio SDK Manager.
Update proto files in Cocos Creator 3D
masterTo update the generated JavaScript and TypeScript definitions from your
.protofiles, follow these steps:Initial Setup: If you haven't already, install the necessary dependencies in the compilation tool directory:
cd tools/compile-proto npm installRebuild Definitions: Every time you modify your
.protofiles, run the build script to regenerate theawesome.jsandawesome.d.tsfiles:cd tools/compile-proto npm run build-proto
cd tools/compile-proto npm run build-proto