cocos2d-x 摇杆(一)

前端之家收集整理的这篇文章主要介绍了cocos2d-x 摇杆(一)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


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();
}

猜你在找的Cocos2d-x相关文章