1 helloworldsence.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::Scene
{
public:
// 初始化
static cocos2d::Scene* createScene();
// 静态创建场景函数
virtual bool init();
// 菜单回调函数
void menuCloseCallback(cocos2d::Ref* pSender);
// 自动创建代码,创建失败会自动回收,如果不能回收会删除
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
2 helloworldsence.cpp
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
// 创建场景
Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}
//当文件不存在时,打印有用的错误消息而不是分段错误。
static void problemLoading(const char* filename)
{
printf("Error while loading: %s\n", filename);
printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}
// 初始化
bool HelloWorld::init()
{
//初始化父类
if ( !Scene::init() )
{
return false;
}
//获取OpenGL视图可见大小
auto visibleSize = Director::getInstance()->getVisibleSize();
//获取OpenGL视图可见方向
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//添加一个带有“X”图像的菜单项,单击该按钮退出程序。可以修改它。
//添加一个“关闭”图标退出进程。这是一个自动保存对象。
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));// 绑定回调函数
if (closeItem == nullptr ||
closeItem->getContentSize().width <= 0 ||
closeItem->getContentSize().height <= 0)
{
problemLoading("'CloseNormal.png' and 'CloseSelected.png'");
}
else
{
float x = origin.x + visibleSize.width - closeItem->getContentSize().width/2;
float y = origin.y + closeItem->getContentSize().height/2;
closeItem->setPosition(Vec2(x,y));
}
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
//添加标签显示“Hello World”
//创建和初始化标签
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
if (label == nullptr)
{
problemLoading("'fonts/Marker Felt.ttf'");
}
else
{
// 把标签放在屏幕的中心
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
//将标签作为子添加到此层
this->addChild(label, 1);
}
// 添加HelloWorld到屏幕上
auto sprite = Sprite::create("HelloWorld.png");
if (sprite == nullptr)
{
problemLoading("'HelloWorld.png'");
}
else
{
//将精灵定位在屏幕的中心。
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
// 将标签作为子添加到此层
this->addChild(sprite, 0);
}
return true;
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
//关闭COCOS2D-X游戏场景并退出应用程序
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
/*To navigate back to native iOS screen(if present) without quitting the application ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/
//EventCustom customEndEvent("game_scene_close_event");
//_eventDispatcher->dispatchEvent(&customEndEvent);
}