测试代码环境:
VS2013 + cocos 2d x 3.0
1、AppDelegate::applicationDidFinishLaunching()
2、创建场景createScene。
3、导演执行runWithScene
导演:
CCDirector获取:
auto director = Director::getInstance();
导演可以获取到视图信息,以及对视图显示相关项进行配置等。
获取界面可视区域大小
Director::getInstance()->getVisibleSize();
场景:
一个界面为一个场景。场景继承于层Layer。
导演控制场景的显示,场景有多层,没层里有许多精灵,精灵有各种动作。
很常用的类如下:
Director Scene Layer Sprite
如何自定义场景?
答:
1、首先派生自public cocos2d::Layer。
2、让场景自动释放。CREATE_FUNC(MyAppScene);
3、添加创建场景实现。
static cocos2d::Scene* createScene()
{
cocos2d::Scene* MyAppScene::createScene()
{
// 自动释放的场景
auto scene = Scene::create();
// 自动释放的层
auto layer = MyAppScene::create();
// 场景中添加层
scene->addChild(layer);
// 返回场景
return scene;
}
}
4、重写虚函数 virtual bool init() override; 在场景里添加精灵。
bool MyAppScene::init()
{
if (!Layer::init())
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
// 新建精灵
auto sprite = Sprite::create("dk_quit_game_bg.9.png");
// 设置瞄点位置
sprite->setAnchorPoint(ccp(0.5, 0.5));
// 设置图片位置
sprite->setPosition(ccp(visibleSize.width / 2.0, visibleSize.height / 2.0));
// 添加精灵到场景
this->addChild(sprite);
return true;
}
如何添加按钮以及相应按钮事件?
答:1、可用图片式按钮,需要准备两张图片,正常情况和鼠标按下的情况。
定义一个签名为 void OnStartButtonMenu(cocos2d::CCObject* pSender); 的事件响应函数。
// 图片式按钮
auto startmenu = CCMenuItemImage::create("button.png",
"button_p.png",
this,
menu_selector(MyAppScene::OnStartButtonMenu));
// 文本式按钮
auto starmenuitemfont = CCMenuItemFont::create("On", this, menu_selector(MyAppScene::OnStart