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>

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...