cocos2d-x学习之触摸移动

来源:互联网 发布:js获取视频的总时间长 编辑:程序博客网 时间:2024/05/11 01:35
游戏中控制人物行走的可以通过方向按键,也可以通过触摸屏幕轨迹来控制人物行走。


现在我们就来看看cocos2d-x引擎是怎样通过处理触摸屏幕事件来实现控制人物移动的。


在HelloWorld.h文件中 重写一下函数:

    virtual void registerWithTouchDispatcher();        //注册触摸事件    virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);  //触摸开始    virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);   //触摸移动


在HelloWorld.cpp文件中:


 初始化函数init()中添加:


 //添加精灵CCSprite *spriteTest = CCSprite::create("aa.png"); spriteTest->setPosition(ccp(200,200));this->addChild(spriteTest,0,520);//使能触摸this->setTouchEnabled(true);  

  

registerWithTouchDispatcher函数:

void HelloWorld::registerWithTouchDispatcher(){   //单点触摸   CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);}


ccTouchBegan函数:


bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent){CCRect rect = this->getChildByTag(520)->boundingBox(); //获取精灵形状位置if(!rect.containsPoint(convertTouchToNodeSpace(pTouch)))  //判断触摸点是否为精灵范围{return false;}return true;}



ccTouchMoved函数:
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent){        //控制精灵在屏幕范围内移动CCSize winSize = CCDirector::sharedDirector()->getWinSize();CCSize heroSize = this->getChildByTag(520)->getContentSize();CCPoint pos = pTouch->getLocation();if(pos.x>winSize.width-heroSize.width/2){pos.x=winSize.width-heroSize.width/2;}if(pos.y>winSize.height-heroSize.height/2){pos.y=winSize.height-heroSize.height/2;}if(pos.x<heroSize.width/2){pos.x=heroSize.width/2;}if(pos.y<heroSize.height/2){pos.y=heroSize.height/2;}//移动精灵this->getChildByTag(520)->setPosition(ccp(pos.x,pos.y));}

这样精灵就可以随着触摸轨迹移动了,希望对大家有帮助。










0 0
原创粉丝点击