Cocos2dx 3.2 横版过关游戏Brave学习笔记(三)

来源:互联网 发布:php与python交互 编辑:程序博客网 时间:2024/05/16 09:02
触摸响应


原版的第二篇包含了动画和触摸响应。动画部分我费了好大工夫才搞定,所以就先把那部分当作第二篇了。另外我发现原来的教程基本上不会大段贴代码,只是把道理讲清楚,代码可以自己下载了慢慢看。我觉得我也应该这样,如果上来就读大段代码,反而容易让人厌倦。


为了方便进行,代码做了些小改动,如将HelloWorld改名为Main,player,enemy1改为私有变量_player,_enemy1,将USING_NS_CC从HelloWorld的cpp文件移动到h文件等等,具体细节可以在:
https://github.com/douxt/Brave_cpp 查看



点击 commits 可以查看所有历史版本以及改动


点击<>便可以查看并下载这个版本的代码。


下一步给MainScene这个Layer添加触摸响应。
先从简单的开始,即触摸屏幕后,player角色会边播放行走动画,并移动到点击的屏幕位置。


给MainScene增加一个EventListenerTouchOneByOne* 类型的_listener_touch
给MainScene.h增加触摸响应函数:
bool onTouchBegan(Touch* touch, Event* event);private:EventListenerTouchOneByOne* _listener_touch;

并在 MainScene::init 里增加:
_listener_touch = EventListenerTouchOneByOne::create();_listener_touch->onTouchBegan = CC_CALLBACK_2(MainScene::onTouchBegan,this);_eventDispatcher->addEventListenerWithSceneGraphPriority(_listener_touch, this);

触摸响应函数实现为:
bool MainScene::onTouchBegan(Touch* touch, Event* event){Vec2 pos = this->convertToNodeSpace(touch->getLocation());_player->walkTo(pos);//log("MainScene::onTouchBegan");return true;}


这里调用了Player类的walkTo函数,还没定义,所以在Player头文件和源文件中定义一下。
void Player::walkTo(Vec2 dest){//stop current moving action, if any.if(_seq)this->stopAction(_seq);auto curPos = this->getPosition();//flip when moving backwardif(curPos.x > dest.x)this->setFlippedX(true);elsethis->setFlippedX(false);//calculate the time needed to moveauto diff = dest - curPos;auto time = diff.getLength()/_speed;auto move = MoveTo::create(time, dest);//lambda functionauto func = [&](){this->stopAllActions();_seq = nullptr;};auto callback = CallFunc::create(func);_seq = Sequence::create(move, callback, nullptr);this->runAction(_seq);this->playAnimationForever(0);}


我曾经想用stopActionTag函数来停止指定的动作,不知为何竟然没成功。这里我索性将动作保存到私有变量_seq中,初始化为nullptr, 并在移动结束的回调中将其赋值为nullptr。
这样如果_seq不为空,则运动正在进行,需要把这个动作停下,否则可能出现多个MoveTo叠加的情况,这不是想要的结果。

然后通过现在位置和目标位置横坐标的比较,决定是否在X方向反转角色。接着根据动作计算所需时间。然后创建MoveTo动作,并定义了一个回调函数func,这是个lambda函数,具体资料可以在网上查到。

然后建立回调动作,将移动和回调组合为序列,然后运行这个序列,并开始播放这个角色的第一个动画walk.


现在运行一下,发现角色会向着点击的方向移动,移动到目的地后,动画会停止播放。

现在的版本为:

https://github.com/douxt/Brave_cpp/tree/51b653b01b5427d985e10483499487d450af31c2







0 0
原创粉丝点击