Cocos2d-x Basics
Scene
Scene is game scene.
You need add at least one scene in your game.
This example is blank scene.
HellWorld.h
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" class HelloWorld : public cocos2d::Layer { public: // there's no 'id' in cpp, so we recommend returning the class instance pointer static cocos2d::Scene* createScene(); // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); // implement the "static create()" method manually CREATE_FUNC(HelloWorld); }; #endif // __HELLOWORLD_SCENE_H__
HelloWorld.cpp
#include "HelloWorldScene.h" USING_NS_CC; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // Add layout }
If you want to add new scene, you need to add file name to jni/Android.mk
LOCAL_SRC_FILES := hellocpp/main.cpp \ ../../Classes/AppDelegate.cpp \ ../../Classes/HelloWorldScene.cpp
Label
auto label = LabelTTF::create("Hello World", "Arial", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1);
Resources
You need to add any images in Resources file in your project root.
In android, images in this directory are copied to assets directory.
Node Enumeration
parent->enumerateChildren("point",[](Node* node) -> bool { // You can get children nodes named "point" as Node class return false; }
Get node by name
Label *title = (Label *)this->getChildByName("title"); // Only one node
Get Current scene and evaluation
Vector<cocos2d::Node *> layers = CCDirector::sharedDirector()->getRunningScene()->getChildren(); for (int i=0; i < layers.size(); i++) { Node *node = layers.at(i); if (instanceof<GamePlayScene>(node)) { //((GamePlayScene *)node)->emergeNativeNode(point); // The Node is Game scene } }
instanceof is class check method, please see instanceOf
String format
Use createWithFormat
const auto str_index = String::createWithFormat("%s%d.png", name, number);