打开 GameScene.h
修整下 GameScene.cpp 写法
#ifndef __GAME_SCENE_H__
#define __GAME_SCENE_H__
#include "cocos2d.h"
#include "knight.hpp"
class GameScene : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
CREATE_FUNC(GameScene);
//实例化对象
TexturePacker::Knight *knightCache = new TexturePacker::Knight();
cocos2d::Sprite *knight = new cocos2d::Sprite();
cocos2d::Animate *knightAnimation = new cocos2d::Animate();
//实例化跳跃动作
cocos2d::Action *jump = new cocos2d::Action();
private:
//新建指针对象listenerKeyboard,指向一个新的键盘监听
cocos2d::EventListenerKeyboard *listenerKeyboard = cocos2d::EventListenerKeyboard::create();
//重载Layer::onKeyPressed
virtual void onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event);
};
#endif // ___GAME_SCENE_H__
打开 GameScene.cpp
...
//knight initialize
//添加到缓存
this->knightCache->addSpriteFramesToCache();
//引用贴图属性方法
knight = this->knightCache->createCha_kni_f_0000Sprite();
//设置舞台位置
knight->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
//引用动画方法
knightAnimation = this->knightCache->createCha_kni_fAnimateAction(0.14f);
//执行动画
knight->runAction(RepeatForever::create(knightAnimation));
//添加到舞台
this->addChild(knight);
//绑定监听回调和对象
listenerKeyboard->onKeyPressed = CC_CALLBACK_2(GameScene::onKeyPressed, this);
//获取事件分发器并添加以节点为顺序的监听器
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listenerKeyboard, this);
...
因为 GameScene 继承 cocos2d::Layer
而 cocos2d::Layer 下已有 onKeyPressed 方法 所以方法必须重载才能定义自己的方法表达式
virtual void onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event);
void GameScene::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event)
{
//判断 keyCode 枚举来区分所按下的按键
switch (keyCode) {
case EventKeyboard::KeyCode::KEY_SPACE:
//新建jump指针,指向JumpBy::create()返回一个Action的指针对象
Action *jump = JumpBy::create(.5, Vec2(0, 0), 20, 1);
//执行,让它跳一下
knight->runAction(jump);
break;
}
}