Control.h
#ifndef_CONTROL_H_ #define_CONTROL_H_ #include"cocos2d.h" USING_NS_CC; classControl:publiccocos2d::CCLayer { public: virtualboolinit(); CREATE_FUNC(Control); virtualvoidonEnter(); virtualvoidonExit(); virtualboolccTouchBegan(CCTouch*touch,CCEvent*event); virtualvoidccTouchMoved(CCTouch*touch,CCEvent*event); virtualvoidccTouchEnded(CCTouch*touch,CCEvent*event); private: CCSizevisibleSize;//可视窗口大小 CCSprite*control_bg; CCSprite*cen; voidinitData(); boolisOnControl; CCPointorigin;//摇杆中心点 floatr_control; }; #endif
#include"Control.h" USING_NS_CC; boolControl::init() { if(!CCLayer::init()) { returnfalse; } initData(); returntrue; } voidControl::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); CCRectr=control_bg->boundingBox(); r_control=(r.getMaxX()-r.getMinX())/2;//摇杆半径 } voidControl::onEnter() { CCLayer::onEnter(); CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,false); } boolControl::ccTouchBegan(CCTouch*touch,CCEvent*event) { if(cen->boundingBox().containsPoint(touch->getLocation())) { isOnControl=true; cen->setScale(1.1); } returntrue; } voidControl::ccTouchMoved(CCTouch*touch,CCEvent*event) { if(isOnControl) { CCPointp_touch=touch->getLocation(); floatdistance=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 { floatx=r_control/distance*(p_touch.x-origin.x)+origin.x; floaty=r_control/distance*(p_touch.y-origin.y)+origin.y; cen->setPosition(ccp(x,y)); cen->setScale(1.1); } } else { //donothing } } voidControl::ccTouchEnded(CCTouch*touch,CCEvent*event) { isOnControl=false; cen->setPosition(origin); cen->setScale(1); } voidControl::onExit() { CCDirector::sharedDirector()->getTouchDispatcher()->removeAllDelegates(); CCLayer::onExit(); }原文链接:https://www.f2er.com/cocos2dx/342565.html