cocos2dx实现手指控制物体移动

前端之家收集整理的这篇文章主要介绍了cocos2dx实现手指控制物体移动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

<span style="font-family:KaiTi_GB2312;font-size:14px;">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,true);
}</span>
原文链接:https://www.f2er.com/cocos2dx/343387.html

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