您的位置:首页 > 移动开发 > Cocos引擎

[cocos2d-x-教程] 让精灵响应触摸 并把方向旋转到相对应的角度

2013-10-16 14:49 411 查看
在cocos2d-x里面  想要把一个精灵从原位置移动到用户所触摸到的点 , 并且把精灵的方向旋转相对应的弧度,可以参考一下我的做法

我这里的精灵是用一条鱼, 用户触摸后鱼就移动到所触摸的点, 并且移动开始时鱼头的方向已经向着所触摸的点 下面是详细做法

首先  h文件申明重写CCLayer里面的四个方法 :

    virtualvoid registerWithTouchDispatcher(void);

   virtualbool ccTouchBegan(CCTouch *pTouch,CCEvent *pEvent);

   virtualvoid ccTouchMoved(CCTouch *pTouch,CCEvent *pEvent);

   virtualvoid ccTouchEnded(CCTouch *pTouch,CCEvent *pEvent);

然后在cpp文件里面的init方法让当前图层实现触摸: 

this->setTouchEnabled(true);

接着在cpp文件里重写的方法实现:

[cpp] view
plaincopy

void StartGame::registerWithTouchDispatcher()  

{  

    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,INT_MIN-1,true);  

}  

bool StartGame::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {  

      

    CCPoint p=pTouch->getLocation();  

    CCSprite * nowsprite=(CCSprite*)this->getChildByTag(888);//根据tag获取我的精灵  

    nowsprite->cocos2d::CCNode::setRotation(atan2((p.x-nowsprite->getPositionX()),(p.y-nowsprite->getPositionY()))*180/3.1415926+90);//改变弧度 后面加不加90要根据精灵的初始角度是怎样的  

    CCMoveTo * move_ten =CCMoveTo::create(1, p); //设定移动所用的时间和坐标  

    nowsprite->runAction(move_ten);  

   return true;  

}  

  

void StartGame::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {  

    CCPoint p=pTouch->getLocation();  

    CCSprite * nowsprite=(CCSprite*)this->getChildByTag(888);  

    nowsprite->setPosition(p);  

}  

void StartGame::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)   

{  

//这里写结束触摸需要实现的功能  

}  

[cpp] view
plaincopy

  





转载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息