原文地址:http://cn.cocos2d-x.org/tutorial/show?id=2201
首先感谢作者Evankaka,再次感谢Cocos2dx官网的推荐,本人只是对作者引擎做些升级,以便Cocos2dx 3.3的用户学习吧
好吧,开始了,跟紧脚步啊,一起熟悉学习Cocos2dx 3.3吧
为了和原文一致,进度都是一样,let‘s go!!
本节内容是 Cocos2d-x虚拟摇杆控制精灵上下左右运动--之游戏《赵云要格斗》
首先,当然是创建工程了,我使用的引擎版本是Cocos2dx 3.3
一、创建游戏工程
1、下载Cocos2dx 3.3 ,并解压
2、点击目录下的setup.py,配置cocos路径,安卓的环境暂时没用到可以先不配
3、win + R打开cmd控制台,输入cocos,可以看到一堆的说明,哈哈,说明环境就Ok罗,
4、创建工程吧!! 控制台输入命令:cocos new HeroFight -p com.chichi.HeroFight -l cpp -d E:\WorkSpace\HeroFight
HeroFight 是游戏名 , -p是包名 ,-l是语言,这里是C++,-d是工程目录的路径
5、哈哈,目录出来了
二、修改背景图片和窗口大小
在AppDelegate中添加,代码中的红色部分即glview->setFrameSize(640, 480);
<span style="color:#333333;"> // initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::create("My Game");
</span><span style="color:#ff0000;">glview->setFrameSize(640, 480);</span><span style="color:#333333;">
director->setOpenGLView(glview);
}</span>
然后在我们要显示的层上HelloWorldScene.cpp的init()函数添加:
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto sprite = Sprite::create("background_1.jpg");
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
this->addChild(sprite, 0);
//摇杆
rocker = HRocker::createHRocker("Direction_bt.png", "Direction_bc.png", Vec2(110, 60));
this->addChild(rocker, 2);
rocker->startRoker(true);
效果图如下
三、添加虚拟摇杆
首先,先将摇杆素材放入到项目的Resources文件夹下,注意,最好把要用到的素材都放在这里,项目工程默认的素材是从此文件夹下查找。
这是摇杆的背景图片,图片不容易找啊。没有美工,只能随便网上找了点,
这是摇杆里面的按钮图片,它是可以移动的。
有了资源当然就可以定义一个摇杆类了,好吧,小伙伴接招吧!!新建一个HRocker.h的头文件,文件的主要实现如下:
#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
}tagDirection;
class HRocker:public Layer
{
public:
HRocker();
~HRocker();
//创建摇杆(摇杆的操作的图片资源名, 摇杆背景图片资源名,起始坐标)
static HRocker* createHRocker(const char *rockerImageName, const char *rockerBGImageName, Vec2 position);
//启动摇杆(显示摇杆、监听摇杆触摸事件)
void startRoker(bool _isStopOther);
//通知摇杆(隐藏摇杆,取消摇杆的触屏监听)
void stopRocker();
//判断控制杆方向,用来判断精灵上、下、左、右运动
int rockerDirection;
//当前人物行走方向,用来判断精灵的朝向,精灵脸朝右还是朝左
bool rockerRun;
CREATE_FUNC(HRocker);
private:
//自定义初始化函数
void rockerInit(const char *rockerImageName, const char *rockerBGImageName, Vec2 position);
//是否可操作摇杆
bool isCanMove;
//获取当前摇杆与用户触屏点的角度
float getRad(Vec2 pos1, Vec2 pos2);
//摇杆背景坐标
Vec2 rockerBGPosition;
//摇杆背景半径
float rockerBGR;
//触屏事件
bool onTouchBegan(Touch *touch, Event *unused_event);
void onTouchMoved(Touch *touch, Event *unused_event);
void onTouchEnded(Touch *touch, Event *unused_event);
};
#endif
然后再创建HRocker.cpp,创建完成后要把 HRocker.cpp和 HRocker.h从proj.win32拷到classes文件中,代码如下:
#include "HRocker.h"
const double PI = 3.1415;
HRocker::HRocker(void)
{
rockerRun = false;
}
HRocker::~HRocker(void)
{
}
HRocker* HRocker::createHRocker(const char *rockerImageName, const char *rockerBGImageName, Vec2 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, const char *rockerBGImageName, Vec2 position)
{
auto spRokerBG = Sprite::create(rockerBGImageName);
spRokerBG->setPosition(position);
spRokerBG->setVisible(false);
addChild(spRokerBG, 0, tag_rockerBG);
auto spRoker = Sprite::create(rockerImageName);
spRoker->setPosition(position);
spRoker->setVisible(false);
addChild(spRoker, 1, tag_rocker);
rockerBGPosition = position;
rockerBGR = spRokerBG->getContentSize().width * 0.5;
rockerDirection = -1;
}
void HRocker::startRoker(bool _isStopOther)
{
auto rocker = (Sprite*)this->getChildByTag(tag_rocker);
rocker->setVisible(true);
auto rockerBG = (Sprite*)this->getChildByTag(tag_rockerBG);
rockerBG->setVisible(true);
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->setSwallowTouches(true);
touchListener->onTouchBegan = CC_CALLBACK_2(HRocker::onTouchBegan, this);
touchListener->onTouchMoved = CC_CALLBACK_2(HRocker::onTouchMoved, this);
touchListener->onTouchEnded = CC_CALLBACK_2(HRocker::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
}
void HRocker::stopRocker()
{
auto rocker = (Sprite*)this->getChildByTag(tag_rocker);
rocker->setVisible(false);
auto rockerBG = (Sprite*)this->getChildByTag(tag_rockerBG);
rockerBG->setVisible(false);
_eventDispatcher->removeEventListenersForTarget(this);
}
float HRocker::getRad(Vec2 pos1, Vec2 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 = py2 - py1;
//算出斜边长度
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;
}
Vec2 getAnglePosition(float r, float angle)
{
return Vec2(r*cos(angle), r*sin(angle));
}
bool HRocker::onTouchBegan(Touch *touch, Event *unused_event)
{
Vec2 point = touch->getLocation();
auto rocker= (Sprite *)this->getChildByTag(tag_rocker);
if (rocker->getBoundingBox().containsPoint(point))
{
isCanMove = true;
CCLOG("begin");
}
return true;
}
void HRocker::onTouchMoved(Touch *touch, Event *unused_event)
{
if (!isCanMove)
{
return;
}
Vec2 point = touch->getLocation();
auto 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(getAnglePosition(rockerBGR, angle), rockerBGPosition));
}
else
{
//当没有超过,让摇杆跟随用户触屏点移动即可
rocker->setPosition(point);
}
//判断方向
if (angle >= -PI/4 && angle < PI/4)
{
rockerDirection = rocker_right;
rockerRun = false;
}
else if(angle >= PI/4 && angle < 3*PI/4)
{
rockerDirection = rocker_up;
}
else if((angle >= 3*PI/4 && angle <= PI) || angle >= -PI && angle < -3*PI/4)
{
rockerDirection = rocker_left;
rockerRun = true;
}
else if (angle >= -3*PI/4 && angle < -PI/4)
{
rockerDirection = rocker_down;
}
}
void HRocker::onTouchEnded(Touch *touch, Event *unused_event)
{
if (!isCanMove)
{
return;
}
auto rockerBG = (Sprite *)this->getChildByTag(tag_rockerBG);
auto rocker = (Sprite *)this->getChildByTag(tag_rocker);
rocker->stopAllActions();
rocker->runAction(CCMoveTo::create(0.08f, rockerBGPosition));
isCanMove = false;
rockerDirection = rocker_stay;
}
哈哈,注释很多,慢慢理解
现在添加HRocker摇杆,打开HelloWorldScene.h添加头文件#include "HRocker.h",加入摇杆类的成员变量
private:
HRocker *rocker;
在HelloWorldScene.cpp的init()函数添加代码如下:
//摇杆
rocker = HRocker::createHRocker("Direction_bt.png", "Direction_bc.png", Vec2(110, 60));
this->addChild(rocker, 2);
rocker->startRoker(true);
效果如下:
四、添加精灵并用摇杆控制’赵云移动‘,激动吧!!!!!!(*^__^*) ~~
这里创建赵云走路的动画,我就顺作者的了,主要就是赵云序列帧用TexturePacker打包图片在一张图片上
这里为了能让精灵运行,我自己创建了一个类Hero,它继承了CCNode,里面实现了动画播放和停止。
赵云的走的动作其实就是一系列的图片合成在一起,
另外,赵云不运动时的图片为这是不运动时精灵的贴图图片。
这里我为了省事,直接用工具TexturePacker将它们打包生成相应的png和plist,这两个合起来在Cocos2d-x可以组成一个动画,比较省事
命名为run_animation.png和run_animation.plist,然后还是把它们放在项目的Resources文件夹下
为了让代码更加容易理解些,我自己创建了一个类, Hero,它继承了CCNode,并且里面有一成员变量 CCSprite* m_HeroSprite;我们就是通过控制它的动画来实现运动的。里面实现了动画播放和停止,好了,代码如下:
#ifndef __HERO_H__
#define __HERO_H__
#include "cocos2d.h"
using namespace cocos2d;
class Hero:public Layer
{
public:
Hero();
~Hero();
//根据图片创建英雄
void InitHeroSprite(char *hero_name);
//设置动画,num为图片数目, run_direction为精灵脸朝向, false朝右, name_each为name——png中的每一小张图片的公共名称部分
void SetAnnimation(const char *name_plist, const char *name_png, const char *name_each, const unsigned int num, bool run_direction);
//停止动画
void StopAnimation();
//判断是否在跑动画
bool IsRunning;
//英雄运动方向
bool HeroDirection;
CREATE_FUNC(Hero);
private:
//精灵
Sprite *m_HeroSprite;
//用来保存初始状态的精灵图片名称
char *Hero_name;
};
#endif //__HERO_H__
Hero.cpp实现如下:
#include "Hero.h"
USING_NS_CC;
Hero::Hero()
{
IsRunning = false;
HeroDirection = false;
Hero_name = NULL;
}
Hero::~Hero()
{
}
void Hero::InitHeroSprite(char *hero_name)
{
Hero_name = hero_name;
this->m_HeroSprite = Sprite::create(hero_name);
this->addChild(m_HeroSprite);
}
//动画播放,可以是跑、攻击、死亡、受伤等
void Hero::SetAnnimation(const char *name_plist, const char *name_png, const char *name_each, const unsigned int num, bool run_direction)
{
if (HeroDirection != run_direction)
{
HeroDirection = run_direction;
m_HeroSprite->setFlippedX(run_direction);
}
if (IsRunning)
return;
//将图片加载到精灵帧缓存池
SpriteFrameCache *m_frameCache = SpriteFrameCache::getInstance();
m_frameCache->addSpriteFramesWithFile(name_plist, name_png);
//用一个列表保存所有的CCSpriteFrameCache
Vector<SpriteFrame*> frameArray;
unsigned int i;
for (i=2; i<=num; i++)
{
SpriteFrame *frame = m_frameCache->getSpriteFrameByName(__String::createWithFormat("%s%d.png", name_each, i)->getCString());
frameArray.pushBack(frame);
}
//使用列表创建动画对象
Animation *animation = Animation::createWithSpriteFrames(frameArray);
if (HeroDirection != run_direction)
{
HeroDirection = run_direction;
}
//表示无限循环播放
animation->setLoops(-1);
//每两张图片的时间隔,图片数目越少,间隔最小就越小
animation->setDelayPerUnit(0.1f);
//将动画包装成一个动作
Animate *animate = Animate::create(animation);
m_HeroSprite->runAction(animate);
IsRunning = true;
}
void Hero::StopAnimation()
{
if (!IsRunning)
{
return;
}
m_HeroSprite->stopAllActions();
//恢复精灵原来的初始化贴图
//把原来的精灵删除掉
this->removeChild(m_HeroSprite, true);
//恢复精灵原来的贴图样子
m_HeroSprite=CCSprite::create(Hero_name);//恢复精灵原来的贴图样子
m_HeroSprite->setFlippedX(HeroDirection);
this->addChild(m_HeroSprite);
IsRunning=false;
}
在HelloWorldScene.h 添加头文件#include "Hero.h",并加入成员变量
private:
Hero *hero;
在HelloWorldScene.h的init()函数添加:
//添加赵云精灵
hero=Hero::create();
hero->InitHeroSprite("zhoayun.png");
hero->setPosition(ccp(200,200));
this->addChild(hero,1);
效果如下:
这时图片还是静止的为了要验证一个精灵的运动,我们来播放一个它的走动的动画,在上面
//英雄
hero = Hero::create();
hero->InitHeroSprite("zhoayun.png");
hero->setPosition(Vec2(200, 200));
this->addChild(hero, 1);
hero->SetAnnimation("run_animation.plist", "run_animation.png", "run_", 8, true);
测试新代码哈哈,这是面朝左的哦,同理朝右为false哦,上图
朝右的我就不上图了。。。
测试完成,我们把这句话去掉吧
//hero->SetAnnimation("run_animation.plist", "run_animation.png", "run_", 8, true);
我们让摇杆让赵云动起来吧,激动吧(*^__^*) ~~
什么动起来,好像很高大上啊,其实就是播放动画的时候播移动精灵的位置,当然也要判断赵云的脸朝向,上面的摇杆类HRocker中
//判断控制杆方向,用来判断精灵上、下、左、右运动
int rockerDirection;
//当前人物行走方向,用来判断精灵的朝向,精灵脸朝右还是朝左
bool rockerRun;
我们只要将这两个参数传给赵云的英雄类的Hero中
//动画播放,可以是跑、攻击、死亡、受伤等
void Hero::SetAnnimation(const char *name_plist, const char *name_png, const char *name_each, const unsigned int num, bool run_direction)
如上的函数里的一个是bool类型,这是精灵的朝向,哈哈刚好用HRocker中的朝向
前面在HelloWorldScene.h中不是创建两个对象
private:
Hero *hero;
HRocker *rocker;
void update(float delta);
此时要在英雄创建的后面开启定时器
<span style="white-space:pre"> </span>//英雄
hero = Hero::create();
hero->InitHeroSprite("zhoayun.png");
hero->setPosition(Vec2(200, 200));
this->addChild(hero, 1);
hero->SetAnnimation("run_animation.plist", "run_animation.png", "run_", 8, true);
this->scheduleUpdate();
哈哈,然后实现update函数里面的方法就行了
void HelloWorld::update(float delta)
{
switch (rocker->rockerDirection)
{
case 1:
hero->SetAnnimation("run_animation.plist", "run_animation.png", "run_", 8, rocker->rockerRun);
hero->setPosition(Vec2(hero->getPositionX()+1, hero->getPositionY()));
break;
case 2:
hero->SetAnnimation("run_animation.plist", "run_animation.png", "run_", 8, rocker->rockerRun);
hero->setPosition(Vec2(hero->getPositionX(), hero->getPositionY() + 1));
break;
case 3:
hero->SetAnnimation("run_animation.plist", "run_animation.png", "run_", 8, rocker->rockerRun);
hero->setPosition(Vec2(hero->getPositionX()-1, hero->getPositionY()));
break;
case 4:
hero->SetAnnimation("run_animation.plist", "run_animation.png", "run_", 8, rocker->rockerRun);
hero->setPosition(Vec2(hero->getPositionX(), hero->getPositionY() - 1));
break;
default:
hero->StopAnimation();
break;
}
}
到此我们run一下吧,哈哈,赵云动起来了,但是还比较傻,后面章节将更加有趣!!
好了到此第一章就结束了!!