项目git地址:https://github.com/marco115/NoOneDies.git
前几篇文章已经把边界框,游戏人物和滑块的运动给做出来了,我们现在就要做游戏的交互
- 负责控制对象逻辑工具类
- 点击事件的处理
负责控制对象逻辑工具类
主要负责实现滑块出现逻辑,添加边界框和游戏人物,并添加实现点击事件
1.1 首先创建一个GameController头文件继承自Ref,同时声明了初始化方法和创建方法
<pre>
class GameControll:public Ref
{
private:
float _postion;
Layer * _layer;
Size visiableSize;
int currentIndexFrame;//当前帧数
int nextIndexCount;//下一个要触发这个事件的帧数
EdgeBox* edge;
Hero* hero;
private:
void resetFrame();
void addBlock();
public:
//虚函数
virtual bool init(Layer * layout,float positionY);
static GameControll* create(Layer* layout,float position);
bool hitTestPoint(Vec2 vector);//是否与触摸点碰撞
void onUserTouch();
void onUpdate(float dt);
};
</pre>
在cpp文件内实现create方法,并初始化GameController
1.2 在初始化方法内,添加边界框和游戏人物
<pre>
GameControll * GameControll::create(Layer * layout, float position)
{
auto _ins = new GameControll();
_ins->init(layout, position);
_ins->autorelease();
return _ins;
}
bool GameControll::init(Layer * layer, float positionY)
{
_layer = layer;
_postion = positionY;
visiableSize = Director::getInstance()->getVisibleSize();
//添加边界框
edge = EdgeBox::create();
edge->setContentSize(visiableSize);
edge->setPosition(visiableSize.width / 2, visiableSize.height / 2+ positionY);
edge->setContentSize(visiableSize);
layer->addChild(edge);
//添加人物
std::string roleName = UserDefault::getInstance()->getStringForKey("HeroRoleName");
hero = Hero::create();
hero->setPosition(30, positionY);
hero->setRoleName(roleName);
layer->addChild(hero);
//添加地板
auto ground = Sprite::create();
ground->setColor(Color3B(0, 0,0));
ground->setTextureRect(Rect(0, 0, visiableSize.width, 3));
ground->setPosition(visiableSize.width / 2, 1.5+positionY);
layer->addChild(ground);
resetFrame();
return true;
}
</pre>
之后在Scene内添加GameController
<pre>
gcs.insert(0, GameControll::create(this, 0));
</pre>
1.3 设置滑块出现的时机,每隔多久出现一块,让滑块出现后则重置出现逻辑
<pre>
void GameControll::onUpdate(float dt)
{
currentIndexFrame++;
if (currentIndexFrame >= nextIndexCount) {
resetFrame();
addBlock();
}
}
void GameControll::resetFrame()
{
currentIndexFrame = 0;
nextIndexCount = rand()% 120 + 60;
}
</pre>
点击事件的处理
首先判断点击的地方是在边界框内,点击后游戏角色进行跳跃
<pre>
bool GameControll::hitTestPoint(cocos2d::Vec2 point) {
bool contain = edge->getBoundingBox().containsPoint(point);
return edge->getBoundingBox().containsPoint(point);
}
void GameControll::onUserTouch() {
hero->getPhysicsBody()->setVelocity(Vec2(0, 400));
}
</pre>
在Scene内添加点击事件监听
<pre>
//添加触摸事件
auto touch = EventListenerTouchOneByOne::create();
touch->onTouchBegan = [this](Touch * t, Event * e) {
for (auto it = gcs.begin(); it != gcs.end(); it++) {
if ((it)->hitTestPoint(t->getLocation())) {
(it)->onUserTouch();
break;
}
}
return false;
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touch, this);
</pre>
添加监听器后,就可以尝试这点击边界框跳动了
对文章有什么优化改进的地方,请留言!谢谢大家