最近想做一款飞机游戏练习一下,在实现飞机拖动的过程中有点小波折,记录一下。
找到偶尔e网事的文章:http://blog.csdn.net/jackystudio/article/details/10983089,但代码直接粘过去报了几个错:
将
CCPoint beginLoc = touch->locationInView(touch->view());
改为:
CCPoint beginLoc = touch->getLocationInView();
将
if(CCRect::CCRectContainsPoint(lpSprite->boundingBox(), this->getParent()-> convertTouchToNodeSpace(touch)) == true)
改为:
if(lpSprite->boundingBox().containsPoint(this->getParent()-> convertTouchToNodeSpace(pTouch)) == true)
其中 lsSprite 是已经实现的精灵。
修改后的代码:
bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
return true;
}
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
//获得触摸点初始坐标
CCPoint beginLoc = pTouch->getLocationInView();
beginLoc = CCDirector::sharedDirector()->convertToGL(beginLoc);
//判断鼠标拖拉的区域是否在精灵上
CCSprite* lpSprite = (CCSprite*)this->getChildByTag(10);
if(lpSprite->boundingBox().containsPoint(this->getParent()->convertTouchToNodeSpace(pTouch)) == true)
{
//获得前一个触摸点坐标
CCPoint endLoc = pTouch->getPreviousLocationInView(/*pTouch->view()*/);
endLoc = CCDirector::sharedDirector()->convertToGL(endLoc);
//计算偏移量
CCPoint offSet = ccpSub(beginLoc, endLoc);
//计算精灵坐标加上移动偏移量、并设置精灵位置
CCPoint pos = ccpAdd(lpSprite->getPosition(), offSet);
lpSprite->setPosition(pos);
}
}