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

来源:互联网 发布:linux 进程调度 编辑:程序博客网 时间:2024/05/16 19:24

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

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

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

  virtualvoidregisterWithTouchDispatcher(void);

  virtualboolccTouchBegan(CCTouch *pTouch,CCEvent*pEvent);

  virtualvoidccTouchMoved(CCTouch *pTouch,CCEvent*pEvent);

  virtualvoidccTouchEnded(CCTouch *pTouch,CCEvent*pEvent);


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

this->setTouchEnabled(true);


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

[cpp] view plaincopy
  1. voidStartGame::registerWithTouchDispatcher()
  2. {
  3. CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,INT_MIN-1,true);
  4. }
  5. boolStartGame::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {
  6. CCPoint p=pTouch->getLocation();
  7. CCSprite * nowsprite=(CCSprite*)this->getChildByTag(888);//根据tag获取我的精灵
  8. nowsprite->cocos2d::CCNode::setRotation(atan2((p.x-nowsprite->getPositionX()),(p.y-nowsprite->getPositionY()))*180/3.1415926+90);//改变弧度后面加不加90要根据精灵的初始角度是怎样的
  9. CCMoveTo * move_ten =CCMoveTo::create(1, p); //设定移动所用的时间和坐标
  10. nowsprite->runAction(move_ten);
  11. returntrue;
  12. }
  13. voidStartGame::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {
  14. CCPoint p=pTouch->getLocation();
  15. CCSprite * nowsprite=(CCSprite*)this->getChildByTag(888);
  16. nowsprite->setPosition(p);
  17. }
  18. voidStartGame::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
  19. {
  20. //这里写结束触摸需要实现的功能
  21. }

[cpp] viewplaincopy