在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(); // 添加按键监听 virtual void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event); // implement the "static create()" method manually CREATE_FUNC(HelloWorld);
};
<p> </p> <p></p> <p>在Scene.cpp中代码:</p> <p></p> <pre class="brush:cpp; toolbar: true; auto-links: false;">#include "HelloWorldScene.h" USING_NS_CC; Scene* HelloWorld::createScene(){ auto scene = Scene::create(); auto layer = HelloWorld::create(); scene->addChild(layer); return scene; } // on "init" you need to initialize your instance bool HelloWorld::init(){ if ( !Layer::init() ){ return false; } //注册捕捉监听 auto listener = EventListenerKeyboard::create(); listener->onKeyReleased = CC_CALLBACK_2(HelloWorld::onKeyReleased, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); return true; } void HelloWorld::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event){ switch (keyCode){ case cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE: case cocos2d::EventKeyboard::KeyCode::KEY_BACK: #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); return; #endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif break; default: break; } }
但是编译无法通过,log为:
1>d:programgametestgameclasseshelloworldscene.h(16): error C2653: “EventKeyboard”: 不是类或命名空间名称 (..ClassesHelloWorldScene.cpp)1>d:programgametestgameclasseshelloworldscene.h(16): error C2061: 语法错误: 标识符“KeyCode” (…ClassesHelloWorldScene.cpp)
1>d:programgametestgameclasseshelloworldscene.h(16): error C2653: “EventKeyboard”: 不是类或命名空间名称 (…ClassesAppDelegate.cpp)
1>d:programgametestgameclasseshelloworldscene.h(16): error C2061: 语法错误: 标识符“KeyCode” (…ClassesAppDelegate.cpp)
1>d:programgametestgameclasseshelloworldscene.cpp(52): error C2511: “void HelloWorld::onKeyReleased(cocos2d::EventKeyboard::KeyCode,cocos2d::Event *)”:“HelloWorld”中没有找到重载的成员函数
1> d:programgametestgameclasseshelloworldscene.h(6) : 参见“HelloWorld”的声明
<p> </p> </p> <p> 求大神帮忙</p> <p> </p> <p> </p>