Cocos2d-x实现精灵的拖动

在实现微信飞机大战的时候,实现了对飞机的拖动。

//ccTouchBegan必须实现,返回真表示该对象捕获触摸
bool GameplayLayer::ccTouchBegan(CCTouch* pTouch, CCEvent* event)
{
    return true;
}
 
void GameplayLayer::ccTouchMoved(CCTouch *touch, CCEvent *event)
{
    //获得触摸点初始坐标
    CCPoint beginLoc = touch->locationInView(touch->view());
    beginLoc = CCDirector::sharedDirector()->convertToGL(beginLoc);
 
    //判断鼠标拖拉的区域是否在精灵上
    if(CCRect::CCRectContainsPoint(lpSprite->boundingBox(), this->getParent()->convertTouchToNodeSpace(touch)) == true)
    {
        //获得前一个触摸点坐标
        CCPoint endLoc = touch->previousLocationInView(touch->view());
        endLoc = CCDirector::sharedDirector()->convertToGL(endLoc);
 
        //计算偏移量
        CCPoint offSet = ccpSub(beginLoc, endLoc);
        Drag(offSet);
    }
 
}
 
void GamePlayLayer::Drag(CCPoint offSet)
{
    //计算精灵坐标加上移动偏移量、并设置精灵位置
    CCPoint pos = ccpAdd(lpSprite->getPosition(), offSet);
    lpSprite->setPosition(pos);
}


你可能感兴趣的:(drag,精灵拖动,CCTouchMoved)