cocos2dx实现手指控制物体移动

   在游戏设计中,经常会涉及到用手指控制游戏主角的移动,下面就是其cocos2dx的实现(基于cocos2dx2.1.4)

bool MainScene::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent){
	CCPoint point = pTouch->getLocationInView();
	point = CCDirector::sharedDirector()->convertToGL(point);
	previousPoint = CCPointMake(point.x,point.y);
	return true;
}
void MainScene::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent){
	//static CCPoint previousPoint;
	CCPoint curpos = pTouch->getLocationInView();
	curpos = CCDirector::sharedDirector()->convertToGL(curpos);

	//重新添加触摸移动代码
	CCPoint mPoint = m_player->getPosition();
	CCPoint distaceXY = CCPointMake(mPoint.x-curpos.x,mPoint.y-curpos.y);
	float xx = curpos.x-previousPoint.x;
	float yy = curpos.y-previousPoint.y;
	previousPoint = CCPointMake(curpos.x,curpos.y);
	if(mPoint.x+xx >= 770 || mPoint.x+xx <= 90 || mPoint.y+yy <= 40 || mPoint.y+yy >= 440){
		if((mPoint.x+xx <= 90 && mPoint.y+yy >= 440) || (mPoint.x+xx <= 90 && mPoint.y+yy <= 40) || (mPoint.x+xx >= 770 && mPoint.y+yy >= 440) || (mPoint.x+xx >= 770 && mPoint.y+yy <= 40)){
			m_player->setPosition(mPoint.x,mPoint.y);
		}else{
		if(mPoint.x+xx >= 770 && xx > 0){
			m_player->setPositionY(mPoint.y+yy);
		}
		if(mPoint.x+xx <= 90 && xx < 0){
			m_player->setPositionY(mPoint.y+yy);
		}
		if(mPoint.y+yy >= 440 && yy > 0){
			m_player->setPositionX(mPoint.x+xx);
		}
		if(mPoint.y+yy <= 40 && yy < 0){
			m_player->setPositionX(mPoint.x+xx);
		}
		}
	}else{
		m_player->setPosition(ccp(mPoint.x+xx,mPoint.y+yy));
	}

}
void MainScene::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent){
	this->setSpeed(0,0);
}
void MainScene::registerWithTouchDispatcher(){
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
}


 

你可能感兴趣的:(软件设计,游戏,cocos2dx)