How to drag a sprite in cocos2d-x | Techbirds
bool HelloWorld::isTouchingSprite(CCTouch* touch)
{
if(tag==1)
return (ccpDistance(ball->getPosition(), this->touchToPoint(touch)) < 100.0f);
}
CCPoint HelloWorld::touchToPoint(CCTouch* touch)
{
// convert the touch object to a position in our cocos2d space
return CCDirector::sharedDirector()->convertToGL(touch->getLocationInView());
}
void HelloWorld::ccTouchesBegan(CCSet* touches, CCEvent* event)
{
this->touchOffset = CCPointZero;
CCTouch* touch = (CCTouch*)(touches->anyObject());
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
if(ball->boundingBox().containsPoint(location)&&ball->getTag()==1)
{
tag=1;
if( touch && this->isTouchingSprite(touch) )
{
this->touchOffset = ccpSub(ball->getPosition(),
this->touchToPoint(touch));
}
}
}
void HelloWorld::ccTouchesMoved(CCSet* touches, CCEvent* event)
{
CCTouch* touch = (CCTouch*)(touches->anyObject());
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
if( touch && touchOffset.x && touchOffset.y )
{
if(tag==1)
this->ball->setPosition(ccpAdd(this->touchToPoint(touch), this->touchOffset));
}
}
void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
CCTouch* touch = (CCTouch*)(touches->anyObject());
this->ball->setPosition(ccpAdd(this->touchToPoint(touch), this->touchOffset));
}