效果图如下,点击到 PLAY 则切换场景
所用到的图片资源:
步骤:
1.创建一个Cocos2d-x工程,保证能成功运行
2.在HelloWorldScene.h文件中添加代码
3.在HelloWorldScene.cpp文件中修改和添加代码
1.创建一个Cocos2d-x工程,将所用到的图片资源添加到工程中,保证能成功运行
2.在HelloWorldScene.h文件中添加代码:
virtual void registerWithTouchDispatcher(); virtual bool ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event); public: CCRect mPlayBounds;
删除bool HelloWorld::init()下do代码块中的所有代码,替换为:
CC_BREAK_IF(! CCLayer::init()); CCSize size = CCDirector::sharedDirector()->getWinSize(); //实例化一个精灵 CCSprite *mMainMenu = CCSprite::create("items.png", CCRectMake(0, 224, 300, 110)); CC_BREAK_IF(!mMainMenu); //设置精灵的位置 mMainMenu->setPosition(ccp(size.width / 2, size.height / 2)); this->addChild(mMainMenu); //绘制一个矩形 mPlayBounds = CCRectMake(size.width / 2 - 64, size.height / 2 + 18, 128, 36); //设置为可触摸 this->setTouchEnabled(true); bRet = true;
void HelloWorld::registerWithTouchDispatcher() { //注册触摸监听 CCDirector* pDirector = CCDirector::sharedDirector(); pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true); } bool HelloWorld::ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event) { //取得触摸点 CCPoint location = touch->getLocationInView(); //将触摸点转换为GL坐标系的点 location = CCDirector::sharedDirector()->convertToGL(location); //如果触摸点在矩形范围内则执行代码,切换场景 if (mPlayBounds.containsPoint(location)) { CCScene *scene = SecondScene::scene(); CCDirector::sharedDirector()->replaceScene(CCTransitionJumpZoom::create(1.0f,scene)); } return true; }