Cocos2d-x虚拟摇杆控制精灵上下左右运动----之游戏开发《赵云要格斗》(1) cocos2dx 3.3移植版

Cocos2d-x虚拟摇杆控制精灵上下左右运动----之游戏开发《赵云要格斗》(1) cocos2dx 3.3移植版,第1张

概述第0章,环境的搭建:: cocos2d-x版本:3.3 工程环境:ubuntu14.04+QTCreator3.3.0 一 创建工程 cocos new ZhaoYun -p com.ARPG.ZhaoYun -l cpp -d ~/ARPG 二 编译并运行。 命令行下: cocos run -s ~/ARPG/ZhaoYun/ -p linux 用QTCreator下: QTCreator打开,

第0章,环境的搭建::

cocos2d-x版本:3.3 工程环境:ubuntu14.04+QTCreator3.3.0

一 创建工程 cocos new ZhaoYun -p com.ARPG.ZhaoYun -l cpp -d ~/ARPG

二 编译并运行。

命令行下: cocos run -s ~/ARPG/ZhaoYun/ -p linux

用QTCreator下: QTCreator打开, file->open file or project,选中 ~\ARPG\ZhaoYun的 CMakeLists.txt,d出配置框,选择编译路径,点击“run cmake”,完成导入后点击 ”finish“. 然后就可以在QTCreator编辑,编译运行。

源码:[email protected]:baIDang201/ARPG_Zhaoyun.git


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////下面是搬运的

@H_301_26@转载请注明出处http://www.jb51.cc/article/p-getkrcwn-kh.html

目录:

一、修改背景图片和窗口大小

二、添加虚拟摇杆
@H_301_26@

三、添加精灵并用摇杆控制精灵的运动

四、思路总结

五、移植总结



一、修改背景图片和窗口大小

首先修改下窗口的大小,在Classes/AppDelegate.cpp中改

[cpp] view plain copy glvIEw = GLVIEwImpl::create("My Game");
glvIEw = GLVIEwImpl::createWithRect("My Game",Rect(0,640,480));

然后在我们要显示的层上HelloWorldScene.cpp的init()函数添加:

    visibleSize = Director::getInstance()->getVisibleSize();
    origin = Director::getInstance()->getVisibleOrigin();
 
    //修改背景图片
    Sprite* pSprite = Sprite::create("background_1.jpg");
    pSprite->setposition(ccp(visibleSize.wIDth/2 + origin.x, visibleSize.height/2 + origin.y));
    this->addChild(pSprite, 0);//这里的0表示放在最底层

效果如下:


二、添加虚拟摇杆

首先,先将摇杆素材放入到项目的Resources文件夹下,注意,最好把要用到的素材都放在这里,项目工程默认的素材是从此文件夹下查找。

这是摇杆的背景图片,图片不容易找啊。没有美工,只能随便网上找了点,

这是摇杆里面的按钮图片,它是可以移动的

好了,接下来我们要开始加入摇杆的进入背景中了,我的思路是把摇杆封装成一个类,然后照看继承cclayer,就可以响应触摸事件了,看看代码,新建一个HRocker.h头文件。这里要注意要把.cpp和.h都放到项目的class文件夹下,要不会提示找不到文件。代码如下:

#ifndef __HROCKER_H__
#define __HROCKER_H__
 
#include "cocos2d.h"
 
using namespace cocos2d;
 
//用于标识摇杆与摇杆的背景
typedef enum{
	tag_rocker,
	tag_rockerBG,
}tagForHRocker;
//用于标识摇杆方向
typedef enum{
	rocker_stay,
	rocker_right,
	rocker_up,
	rocker_left,
	rocker_down,
}tagDirecton;
 
class HRocker:public cclayer
{
public:
	HRocker(voID);
	~HRocker(voID);
 
	//创建摇杆(摇杆的 *** 作题图片资源名,摇杆背景图片资源名,起始坐标)
	static HRocker* createHRocker(const char *rockerImagename,const char *rockerBGImagename,CCPoint position);
	//启动摇杆(显示摇杆、监听摇杆触屏事件)
	voID startRocker(bool _isstopOther);
	//停止摇杆(隐藏摇杆,取消摇杆的触屏监听)
	voID stopRocker();
	//判断控制杆方向,用来判断精灵上、下、左、右运动
	int rocketDirection;
	//当前人物行走方向,用来判断精灵的朝向,精灵脸朝右还是朝左
	bool rocketRun;
	CREATE_FUNC(HRocker);
private:
	//自定义初始化函数
	voID rockerInit(const char* rockerImagename,const char* rockerBGImagename,CCPoint position);
	//是否可 *** 作摇杆
	bool isCanMove;
	//获取当前摇杆与用户触屏点的角度
	float geTrad(CCPoint pos1,CCPoint pos2);
 
    CCPoint getAngeleposition(float r,float angle);
 
	//摇杆背景的坐标
	CCPoint rockerBGposition;
	//摇杆背景的半径
	float rockerBGR;
 
};
 
#endif
         

再建其相应的实现HRocker.cpp,这里要注意要把.cpp和.h都放到项目的class文件夹下,要不会提示找不到文件。代码如下:

#include "HRocker.h"
const double PI=3.1415;
HRocker::HRocker(voID)
{
	rocketRun=false;
}
 
HRocker::~HRocker(voID)
{
}
 
//创建摇杆(摇杆的 *** 作题图片资源名,摇杆背景图片资源名,起始坐标)
HRocker* HRocker::createHRocker(const char *rockerImagename,CCPoint position)
{
	HRocker *layer = HRocker::create();
	if (layer)
	{
		layer->rockerInit(rockerImagename,rockerBGImagename,position);
		return layer;
	}
	CC_SAFE_DELETE(layer);
	return NulL;
}
 
//自定义初始化函数
voID HRocker::rockerInit(const char* rockerImagename,CCPoint position)
{
	Sprite *spRockerBG = Sprite::create(rockerBGImagename);
	spRockerBG->setposition(position);
	spRockerBG->setVisible(false);
	addChild(spRockerBG,0,tag_rockerBG);
 
	Sprite *spRocker = Sprite::create(rockerImagename);
	spRocker->setposition(position);
	spRocker->setVisible(false);
	addChild(spRocker,1,tag_rocker);
 
	rockerBGposition = position;
	rockerBGR = spRockerBG->getContentSize().wIDth*0.5;//
	rocketDirection=-1;//表示摇杆方向不变
}
 
//启动摇杆(显示摇杆、监听摇杆触屏事件)
voID HRocker::startRocker(bool _isstopOther)
{
	Sprite *rocker = (Sprite*)this->getChildByTag(tag_rocker);
	rocker->setVisible(true);
 
	Sprite *rockerBG = (Sprite *)this->getChildByTag(tag_rockerBG);
	rockerBG->setVisible(true);
 
    auto Listenertouch = EventListenertouchOneByOne::create();//创建一个触摸监听
    Listenertouch->setSwallowtouches(true);//设置是否想下传递触摸
 
 
    //3.0 后可以直接在touchBegan后添加它的实现代码,而不用特意去写一个touchBegan的函数
    Listenertouch->ontouchBegan = [=](touch* touch, Event* event){ //[]中间的是传入的参数
        CCPoint point = touch->getLocation();
        Sprite *rocker = (Sprite *)this->getChildByTag(tag_rocker);
        if (rocker->boundingBox().containsPoint(point))
            isCanMove = true;
        return true;
    };
 
    //拖动精灵移动
    Listenertouch->ontouchmoved = [this](touch* touch, Event* event){
        if (!isCanMove)
        {
            return;
        }
        CCPoint point = touch->getLocation();
        Sprite *rocker = (Sprite *)this->getChildByTag(tag_rocker);
        //得到摇杆与触屏点所形成的角度
        float angle = geTrad(rockerBGposition,point);
        //判断两个圆的圆心距是否大于摇杆背景的半径
        if (sqrt(pow((rockerBGposition.x - point.x),2) + pow((rockerBGposition.y - point.y),2)) >= rockerBGR)
        {
            //保证内部小圆运动的长度限制
            rocker->setposition(ccpAdd(getAngeleposition(rockerBGR,angle),ccp(rockerBGposition.x,rockerBGposition.y)));
        }
        else
        {
            rocker->setposition(point);
        }
 
        //判断方向
        if(angle>=-PI/4&&angle<PI/4)
        {
            rocketDirection=rocker_right;
            rocketRun=false;
        }
        else if(angle>=PI/4&&angle<3*PI/4)
        {
            rocketDirection=rocker_up;
        }
        else if((angle>=3*PI/4&&angle<=PI)||(angle>=-PI&&angle<-3*PI/4))
        {
            rocketDirection=rocker_left;
            rocketRun=true;
        }
        else if(angle>=-3*PI/4&&angle<-PI/4)
        {
            rocketDirection=rocker_down;
        }
    };
 
    Listenertouch->ontouchended = [=](touch* touch, Event* event){ // =在c++11里面代表这个lambda表达式中能使用外面的变量
//        if (!isCanMove)
//        {
//            return;
//        }
        Sprite *rockerBG = (Sprite*)this->getChildByTag(tag_rockerBG);
        Sprite *rocker = (Sprite*)this->getChildByTag(tag_rocker);
        rocker->stopAllActions();
        rocker->runAction(CCMoveto::create(0.08f,rockerBG->getposition()));
        isCanMove = false;
        rocketDirection=rocker_stay;
    };
 
 
    auto ListenerKey = EventListenerKeyboard::create();//创建一个触摸监听
    ListenerKey->onKey@R_404_4848@ = [this](EventKeyboard::KeyCode code, Event* event)
    {
        //isCanMove = true;
        switch(code)
        {
        case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
            rocketDirection=rocker_right;
            rocketRun=false;
            break;
        case EventKeyboard::KeyCode::KEY_UP_ARROW:
            rocketDirection=rocker_up;
            break;
        case EventKeyboard::KeyCode::KEY_left_ARROW:
            rocketDirection=rocker_left;
            rocketRun=true;
            break;
        case EventKeyboard::KeyCode::KEY_DOWN_ARROW:
            rocketDirection=rocker_down;
            break;
        default:
            break;
        }
        log("press key");
    };
 
    ListenerKey->on@R_502_3660@d = [this](EventKeyboard::KeyCode code, Event* event)
    {
        Sprite *rockerBG = (Sprite*)this->getChildByTag(tag_rockerBG);
        Sprite *rocker = (Sprite*)this->getChildByTag(tag_rocker);
        rocker->stopAllActions();
        rocker->runAction(CCMoveto::create(0.08f,rockerBG->getposition()));
        //isCanMove = false;
        rocketDirection=rocker_stay;
        log("released key");
    };
 
 
    //将触摸监听添加到eventdispacher中去
    _eventdispatcher->addEventListenerWithSceneGraPHPriority(Listenertouch ,this);
    _eventdispatcher->addEventListenerWithSceneGraPHPriority(ListenerKey ,this);
}
 
//停止摇杆(隐藏摇杆,取消摇杆的触屏监听)
voID HRocker::stopRocker()
{
	Sprite *rocker = (Sprite *)this->getChildByTag(tag_rocker);
	rocker->setVisible(false);
 
	Sprite * rockerBG = (Sprite *)this->getChildByTag(tag_rockerBG);
	rockerBG->setVisible(false);
 
    _eventdispatcher->removeAllEventListeners();
}
 
 
//获取当前摇杆与用户触屏点的角度
float HRocker::geTrad(CCPoint pos1,CCPoint pos2)
{
	float px1 = pos1.x;
	float py1 = pos1.y;
	float px2 = pos2.x;
	float py2 = pos2.y;
 
	//得到两点x的距离
	float x = px2 - px1;
	//得到两点y的距离
	float y = py1 - py2;
	//算出斜边长度
	float xIE = sqrt(pow(x,2) + pow(y,2));
	//得到这个角度的余弦值(通过三角函数中的店里:角度余弦值=斜边/斜边)
	float cosAngle = x / xIE;
	//通过反余弦定理获取到期角度的弧度
	float rad = acos(cosAngle);
	//注意:当触屏的位置Y坐标<摇杆的Y坐标,我们要去反值-0~-180
	if (py2 < py1)
	{
		rad = -rad;
	}
	return rad;
}
 
CCPoint HRocker::getAngeleposition(float r,float angle)
{
	return ccp(r*cos(angle),r*sin(angle));
}
 
         这里的思路我等下再说吧 @H_301_26@ 

之后就在HelloWorldScene.h添加头文件#include "HRocker.h",并加入摇杆类的成员变量

private: HRocker*rocker;
在HelloWorldScene.h的init()函数添加:

	//添加摇杆
	rocker = HRocker::createHRocker("Direction_bt.png","Direction_bc.png",ccp(110,60));//其中第一张图片为摇杆的按钮,第二张为背景
	this->addChild(rocker,2);
	rocker->startRocker(true);

效果如下:我们可以看到,可以移动摇杆了


效果还是不错的,很灵敏,小球也不会跳出

三、添加精灵并用摇杆控制精灵的运动

这里为了能让精灵运行,我自己创建了一个类,Hero,它继承了CCNode,里面实现了动画播放和停止

赵云的走的动作其实就是一系列的图片合成在一起,


另外,赵云不运动时的图片为

zhoayun.png。这是不运动时精灵的贴图图片,

这里我为了省事,直接用工具TexturePacker将它们打包生成相应的png和pList,这两个合起来在cocos2d-x可以组成一个动画,比较省事

命名为run_animation.png和run_animation.pList,然后还是把它们放在项目的Resources文件夹下

为了让代码更加容易理解些,我自己创建了一个类,并且里面有一成员变量CCSprite* m_HeroSprite;我们就是通过控制它的动画来实现运动的。里面实现了动画播放和停止,好了,代码如下

Hero.h

#ifndef __HERO_H__
#define __HERO_H__
#include "cocos2d.h"
#include "cocos-ext.h"
using namespace cocos2d;
USING_NS_CC_EXT; 
 class Hero:public cocos2d::CCNode
 {
 public:
	   Hero(voID);
	  ~Hero(voID);
	 //根据图片名创建英雄
	 voID InitHeroSprite(char *hero_name);
	 //设置动画,num为图片数目,run_directon为精灵脸朝向,false朝右
     voID SetAnimationAdv(const char *name_pList,const char *name_png, const char * actnameInnamePng, unsigned int startIndex, unsigned int num,bool run_directon);
	//停止动画
	 voID StopAnimation();
     //GetHeroPoint
     const Sprite* GetHeroSprite() const;
 
	//判断是否在跑动画
	 bool IsRunning;
	 //英雄运动的方向
	 bool HeroDirecton;
	 CREATE_FUNC(Hero);
 private:
	 Sprite* m_HeroSprite;//精灵
	 char *Hero_name;//用来保存初始状态的精灵图片名称
 };
#endif // __HERO_H__
         

然后是Hero.cpp

#include "Hero.h"
USING_NS_CC; 
USING_NS_CC_EXT;
Hero::Hero(voID)
{
	IsRunning=false;//没在放动画
	HeroDirecton=false;//向右运动
	Hero_name=NulL;
}
 
Hero::~Hero(voID)
{
 
}
 
 voID Hero::InitHeroSprite(char *hero_name)
 {
	Hero_name=hero_name;
	this->m_HeroSprite=CCSprite::create(hero_name);
	this->addChild(m_HeroSprite);
 }
 
 //原地奔跑动画
 voID Hero::SetAnimationAdv(const char *name_pList,bool run_directon)
 {
     if(HeroDirecton!=run_directon)
     {
         HeroDirecton=run_directon;
         m_HeroSprite->setFlipX(run_directon);//trun the sprite
     }
     if(IsRunning)
     {
         return;
     }
     //将图片加载到精灵帧缓存池
    CCSpriteFrameCache *m_frameCache=CCSpriteFrameCache::sharedSpriteFrameCache();
     m_frameCache->addSpriteFramesWithfile(name_pList,name_png);
     //用一个列表保存所有的CCSpriteFrameCache
     Vector<CCSpriteFrame*>  frameArray = Vector<CCSpriteFrame*>();
     unsigned int i;
     for(i=startIndex;i<=num;i++)
     {
         CCSpriteFrame* frame=m_frameCache->spriteFrameByname(CCString::createWithFormat("%s%d.png", actnameInnamePng, i)->getCString());
         frameArray.pushBack(frame);
     }
     //使用列表创建动画对象
     Animation* animation=Animation::createWithSpriteFrames(frameArray);
     if(HeroDirecton!=run_directon)
     {   HeroDirecton=run_directon;
 
     }
     animation->setLoops(-1);//表示无限循环播放
     animation->setDelayPerUnit(0.1f);//每两张图片的时间隔,图片数目越少,间隔最小就越小
 
     //将动画包装成一个动作
     CCAnimate* act=CCAnimate::create(animation);
 
 
     m_HeroSprite->runAction(act);
     IsRunning=true;
 
 }
 
 voID Hero::StopAnimation()
 {
	 if(!IsRunning)
		 return;
	m_HeroSprite->stopAllActions();//当前精灵停止所有动画
 
	//恢复精灵原来的初始化贴图 
    this->removeChild(m_HeroSprite,true);//把原来的精灵删除掉
	m_HeroSprite=Sprite::create(Hero_name);//恢复精灵原来的贴图样子
	m_HeroSprite->setFlipX(HeroDirecton);
	this->addChild(m_HeroSprite);
	IsRunning=false;
	IsRunning=false;
 }
const Sprite* Hero::GetHeroSprite() const
{
    return m_HeroSprite;
}
         
之后就在HelloWorldScene.h添加头文件#include "Hero.h",并加入成员变量

Hero*hero;

 

在HelloWorldScene.h的init()函数添加:

//添加赵云精灵 hero=Hero::create(); hero->InitHeroSprite(@H_301_3547@"zhoayun.png"); hero->setposition(ccp(200,200)); this->addChild(hero,1);
效果如下:

这时图片还是静止的为了要验证一个精灵的运动,我们来播放一个它的走动的动画,在上面 @H_301_26@

hero=Hero::create(); hero->InitHeroSprite(@H_301_3547@"zhoayun.png"); hero->setposition(ccp(200,200)); 添加一句

hero->SetAnimationAdv("run_animation.pList","run_animation.png""run_"28false);@H_502_3655@//8表示pList中的停止图片下标,false表示脸朝右
来看看效果,这时精灵会一直不停的运动


如果我们要改变精灵的脸朝向呢?简单,false改成true hero->SetAnimationAdv("run_animation.pList""run_animation.png""run_"28true);//8表示pList中的图片数目,false表示脸朝右 效果:

好了,验证正确后,我们还不是把上面那一句注释掉,因为精灵应该是我们点了摇杆让他动它才动的。

其实要控制人物的运动很简单,无非是在播房动画的同时,要移动精灵的位置,当然,这里我们也要判断精灵的脸朝向,上面的摇杆类HRocker中

//判断控制杆方向,用来判断精灵上、下、左、右运动 introcketDirection; //当前人物行走方向,用来判断精灵的朝向,精灵脸朝右还是朝左 boolrocketRun;
我们只要将这两个参数传给赵去的英雄类Hero中的

//设置动画,num为图片停止下标号,run_directon为精灵脸朝向,false朝右

voID Hero::SetAnimationAdv(const char *name_pList,bool run_directon)

看到了没,一个刚好是int 型,一个刚好是bool型。那我们要怎么来控制了。前面我们在HelloWorldScene中不是创建了两个对像 HRocker*rocker;//摇杆 Hero*hero;///精灵
将rocker的值传给hero不就可以控制了么?想着要能每帧都能更新,所以在HelloWorldScene.h中加入事件

virtualvoIDupdate(floatdelta);
一定要注意在HelloWorldScene.cpp的init()函数下面添加 //启动updata事件 this->scheduleUpdate(); 然后就是事件了

voID HelloWorld::update(float delta)
{
    int newX = 0;
    int newY = 0;
	//判断是否按下摇杆及其类型
	switch(rocker->rocketDirection)
	{
	case 1:
        hero->SetAnimationAdv("run_animation.pList","run_animation.png", "run_", 2, 8, rocker->rocketRun);
        if(hero->getposition().x+2 + hero->GetHeroSprite()->getContentSize().wIDth/2 > visibleSize.wIDth)
        {
            break;
        }
        hero->setposition(ccp(hero->getposition().x+2,hero->getposition().y)); //向右走
		break;
	case  2:
        hero->SetAnimationAdv("run_animation.pList", rocker->rocketRun);
        if(hero->getposition().y+2 + hero->GetHeroSprite()->getContentSize().height/2 > visibleSize.height)
        {
            break;
        }
        hero->setposition(ccp(hero->getposition().x, hero->getposition().y+2));   //向上走
		break;
	case 3:
        hero->SetAnimationAdv("run_animation.pList", rocker->rocketRun);
        if(hero->getposition().x-2 - hero->GetHeroSprite()->getContentSize().wIDth/2 < 0)
        {
            break;
        }
        hero->setposition(ccp(hero->getposition().x-2,hero->getposition().y));   //向左走
		break;
	case 4:
        if(hero->getposition().y-2 - hero->GetHeroSprite()->getContentSize().height/2 < 0)
        {
            break;
        }
        hero->SetAnimationAdv("run_animation.pList", rocker->rocketRun);
        hero->setposition(ccp(hero->getposition().x,hero->getposition().y-2));   //向下走
		break;
	default:
		hero->StopAnimation();//停止所有动画和运动
		break;
 
    }

好了,我们来看看效果如何 @H_301_26@

效果还不错,也不会很卡。总算大功告成了!
四、思路总结 其实这里的思路是把摇杆类的精灵类分开来实现,摇杆类中有可以控制按钮的运动,并有返回当前你摇杆的 *** 作类型,是向上还是向下,是脸朝右还朝左,然后还这些参数传给英雄精灵类,这里的英雄我们也要设置它的动画,然后就是在创建两个个类的实例对像的层中来调用它们,并在updata()函数中判断摇杆是否按下,及方向,然后设置赵云精灵类的移动的动画的播放。思路就是这样了,由于工程还要一直改下去,如果谁现在想要我的素材和工程的,留个邮箱给我就是了哈,我会发给你们的。
五 移植总结。 1 事件回调的变化

覆写监听虚函数 => lamda表达式+闭包

2.0

virtualboolcctouchBegan(CCtouch*ptouch,CCEvent*pEvent); voID
cctouchmoved(CCtouch*ptouch,CCEvent*pEvent);
voID
cctouchended(CCtouch*ptouch,CCEvent*pEvent);

3.0

Listenertouch->ontouchBegan = [=](touch* touch, Event* event)
Listenertouch->ontouchmoved = [this](touch* touch, Event* event)
Listenertouch->ontouchended = [=](touch* touch, Event* event)


2 函数名2.2.5 到 3.3.0的变化

之前2.0的CC**,把CC都去掉,基本的元素都是保留的 2.0
CCSpriteCCCallFuncCCNode..
3.0
SpriteCallFuncNode..

3shared***改变

2.0 CCSizewinSize=CCDirector::sharedDirector()->getWinSize(); SpriteFrameCache::sharedSpriteFrameCache() AnimationCache::sharedAnimationCache() NotificationCenter::sharednotificationCenter() … 3.0 Sizesize=Director::getInstance()->getWinSize(); SpriteFrameCache::getInstance() AnimationCache::getInstance() NotificationCenter::getInstance() 总结

以上是内存溢出为你收集整理的Cocos2d-x虚拟摇杆控制精灵上下左右运动----之游戏开发《赵云要格斗》(1) cocos2dx 3.3移植版全部内容,希望文章能够帮你解决Cocos2d-x虚拟摇杆控制精灵上下左右运动----之游戏开发《赵云要格斗》(1) cocos2dx 3.3移植版所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1037457.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存