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

在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文件里重写的方法实现:

 

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) 
{
//这里写结束触摸需要实现的功能
}

 

 


 

 

posted on 2013-10-16 13:38  love so much  阅读(513)  评论(0编辑  收藏  举报

导航