您的位置:首页 > 移动开发 > Cocos引擎

cocos2d-x 街机摇杆 实现

2014-03-06 20:59 218 查看
自从2007年乔布斯发布第一款Iphone后,没有物理导航键的多点触控手机流行起来。到现在,不论是IOS、Android还是Wp系统的手机风格依然如此。动作类游戏一直是移动游戏中的重头大戏,如何既能让玩家操作简单、又能有保持的游戏性是设计过程中的重中之重。

模拟摇杆是解决街机类动作游戏中最常见的操作方法,今天的练习最终实现的效果如图所示:


1. 准备工作

首先制作两张图片:白色摇杆面板:

红色摇杆:



2. 基本原理

使用上面两张图片制作出两个精灵、启用触摸监听

当用户在摇杆面板开始触摸、移动后,通过触摸点计算出图中(a,b)坐标:


3. cocos2d-x 3.0 实现代码(C++新手,凑合凑合吧)

USING_NS_CC;
Scene* HelloWorld::scene()
{
Scene *scene = Scene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
HelloWorld::HelloWorld()
{
isDown = false;
}
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Point origin = Director::getInstance()->getVisibleOrigin();
//////////////////////////////
//设置背景
Sprite* background = Sprite::create("Background.png");
background->setAnchorPoint(Point(0,0));
this->addChild(background);
//////////////////////////////
//添加摇杆面板	float r = 48.5; /*摇杆中点坐标距离*/
Sprite* board = Sprite::create("board.png");
board->setPosition(Point(r+30,r+30));
this->addChild(board);
//////////////////////////////
//添加摇杆精灵
Sprite* stick = Sprite::create("stick.png");
stick->setPosition(Point(r+30,r+30));
rect = CCRectMake(30,30,97,97);
this->addChild(stick, 100, 100);
//////////////////////////////
//启用触摸监听
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);

return true;
}
//发生按下事件
bool HelloWorld::ccTouchBegan(Touch *touch, Event *event){

//当用户在摇杆面板按下 (rect是头文件中声明的全局变量,这个rect包含着摇杆面板)
if(rect.containsPoint(touch->getLocation()))
{
//通过编号得到stick摇杆实例
Sprite* stick = (Sprite*)this->getChildByTag(100);
//把触摸点设置为摇杆位置
stick->setPosition(touch->getLocation());
//isDown是全局变量,代表用户是否在操作摇杆
isDown = true;
}
return true;
}
//发生移动事件
void HelloWorld::ccTouchMoved(Touch *touch, Event *event){
//当用户在操作摇杆
if(isDown)
{
Sprite* stick = (Sprite*)this->getChildByTag(100);
//当用户手指在摇杆面板内部
if(rect.containsPoint(touch->getLocation()))
{
stick->setPosition(touch->getLocation());
}
else
{
//摇杆中点坐标距离
float r = 48.5;

float t_x = touch->getLocation().x - r - 30;
float t_y = touch->getLocation().y - r - 30;
float t_z = sqrt(t_x*t_x + t_y*t_y);

float n = r/t_z;

float x = (t_x) * n + r+30;
float y = (t_y) * n + r+30;

stick->setPosition(Point(x, y));
}

//发生抬起事件
void HelloWorld::ccTouchEnded(Touch *touch, Event *event){
float r = 48.5;
Sprite* stick = (Sprite*)this->getChildByTag(100);
//让摇杆归位
stick->setPosition(Point(r+30,r+30));

isDown = false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: