前端之家收集整理的这篇文章主要介绍了
cocos2d-x摇杆(一),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
具体实现:
Control.h
#ifndef _CONTROL_H_
#define _CONTROL_H_
#include "cocos2d.h"
USING_NS_CC;
class Control : public cocos2d::CCLayer
{
public:
virtual bool init();
CREATE_FUNC(Control);
virtual void onEnter();
virtual void onExit();
virtual bool ccTouchBegan(CCTouch* touch,CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch,CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch,CCEvent* event);
private:
CCSize visibleSize; //可视窗口大小
CCSprite* control_bg;
CCSprite* cen;
void initData();
bool isOnControl;
CCPoint origin; //摇杆中心点
float r_control;
};
#endif
Control.cpp
#include"Control.h"
USING_NS_CC;
bool Control::init()
{
if (!CCLayer::init())
{
return false;
}
initData();
return true;
}
void Control::initData()
{
origin = ccp(150,150); //摇杆原点
control_bg = CCSprite::create("dpadUp.png");
control_bg->setPosition(origin);
control_bg->setScale(2);
this->addChild(control_bg);
cen = CCSprite::create("joystickUp.png");
cen->setPosition(origin);
this->addChild(cen);
CCRect r = control_bg->boundingBox();
r_control = (r.getMaxX()-r.getMinX())/2; //摇杆半径
}
void Control::onEnter()
{
CCLayer::onEnter();
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,false);
}
bool Control::ccTouchBegan(CCTouch* touch,CCEvent* event)
{
if (cen->boundingBox().containsPoint(touch->getLocation()))
{
isOnControl = true;
cen->setScale(1.1);
}
return true;
}
void Control::ccTouchMoved(CCTouch* touch,CCEvent* event)
{
if (isOnControl)
{
CCPoint p_touch = touch->getLocation();
float distance = sqrt((p_touch.x - origin.x)*(p_touch.x - origin.x)+(p_touch.y - origin.y)*(p_touch.y - origin.y)); //触摸点和摇杆起点的距离
if (distance <= r_control)
{
cen->setPosition(touch->getLocation());
cen->setScale(1.1);
}
else
{
float x = r_control/distance * (p_touch.x - origin.x)+origin.x;
float y = r_control/distance * (p_touch.y - origin.y)+origin.y;
cen->setPosition(ccp(x,y));
cen->setScale(1.1);
}
}
else
{
//do nothing
}
}
void Control::ccTouchEnded(CCTouch* touch,CCEvent* event)
{
isOnControl = false;
cen->setPosition(origin);
cen->setScale(1);
}
void Control::onExit()
{
CCDirector::sharedDirector()->getTouchDispatcher()->removeAllDelegates();
CCLayer::onExit();
}
在场景中使用:
control = Control::create();
this->addChild(control,1);
代码和素材下载地址:
原文链接:https://www.f2er.com/cocos2dx/342549.html