Cocos2d-x 让飞机随着触摸移动起来

首先要在GameLayer init() 中设置支持单点触摸,然后要重载触摸处理的函数


//设置可触摸
this->setTouchEnabled(true)

重载函数:

	//重载函数,对单点触摸有效
	virtual void registerWithTouchDispatcher();

	virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
	virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);

//重载函数,对单点触摸有效
void GameLayer::registerWithTouchDispatcher()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
}

void GameLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
	if(this->m_planeLayer->isAlive)
	{
		CCPoint beginPoint=pTouch->getLocationInView(); //触摸起点
		beginPoint=CCDirector::sharedDirector()->convertToGL(beginPoint); //把屏幕坐标转换成游戏坐标


		//飞机当前位置  形状位置
		CCRect planeRect=this->m_planeLayer->getChildByTag(AIRPLANE)->boundingBox();

		//如果当前触摸坐标是在飞机的范围内
		if(planeRect.containsPoint(this->getParent()->convertTouchToNodeSpace(pTouch))==true)
		{
			CCPoint endPoint=pTouch->getPreviousLocationInView();//前一个触摸位置
			endPoint=CCDirector::sharedDirector()->convertToGL(endPoint);
			CCPoint offSet=ccpSub(beginPoint,endPoint);
			CCPoint toPoint=ccpAdd(this->m_planeLayer->getChildByTag(AIRPLANE)->getPosition(),offSet);
			this->m_planeLayer->MoveTo(toPoint);
		}
	}
}

飞机的移动

void PlaneLayer::MoveTo(CCPoint location)
{
	if(isAlive&&!CCDirector::sharedDirector()->isPaused())
	{
		//边界判断
		CCPoint actualPoint;
		CCSize winSize=CCDirector::sharedDirector()->getWinSize();
		CCSize planeSize=this->getChildByTag(AIRPLANE)->getContentSize();

		//不能超过最小x y
		if (location.x<planeSize.width/2) //保持机身全部在屏幕内
		{
			location.x=planeSize.width/2;
		}
		if (location.y<planeSize.height/2)
		{
			location.y=planeSize.height/2;
		}

		//不能超过最大x ,y
		if (location.x>winSize.width-planeSize.width/2)
		{
			location.x=winSize.width-planeSize.width/2;
		}
		if (location.y>winSize.height-planeSize.height/2)
		{
			location.y=winSize.height-planeSize.height/2;
		}
		this->getChildByTag(AIRPLANE)->setPosition(location);
	}
}


你可能感兴趣的:(cocos2d-x)