sx1n90
January 26, 2012, 7:56am
#1
I have draggable SpriteA. I start drag when touch began on it, move if touch moving and place on field when touch is ended. Also i have a button SpriteB if touch began on it:
SpriteB hided
SpriteA crated in touch location
SpriteA start draggin
But SpriteA dont dragging because dont receive touch event. How can i pass touch event on it?
PS. Simple calling ccTouchBegan on SpriteA dont work.
PSS. Sorry for my terrible English.
Hi, Serg Merg,
Try my solution below.
class HelloWorld : public cocos2d::CCLayer
{
public:
virtual ~HelloWorld();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommand to return the exactly class pointer
static cocos2d::CCScene* scene();
// a selector callback
virtual void menuCloseCallback(cocos2d::CCObject* pSender);
// implement the "static node()" method manually
LAYER_NODE_FUNC(HelloWorld);
virtual void registerWithTouchDispatcher();
virtual bool ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void ccTouchEnded(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void ccTouchCancelled(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void ccTouchMoved(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
cocos2d::CCSprite* m_pSpriteA;
cocos2d::CCSprite* m_pSpriteB;
bool m_bSpriteBPressed;
};
void HelloWorld::registerWithTouchDispatcher()
{
CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true);
}
bool HelloWorld::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
CCPoint touchLocation = touch->locationInView( touch->view() );
touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
if (CCRect::CCRectContainsPoint(m_pSpriteB->boundingBox(), touchLocation))
{// touch b sprite
m_pSpriteB->setIsVisible(false);
m_bSpriteBPressed = true;
}
return true;
}
void HelloWorld::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
if (m_bSpriteBPressed)
{
CCPoint touchLocation = touch->locationInView( touch->view() );
touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
m_bSpriteBPressed = false;
m_pSpriteB->setIsVisible(true);
m_pSpriteA->setPosition(touchLocation);
}
}
void HelloWorld::ccTouchCancelled(CCTouch* touch, CCEvent* event)
{
}
void HelloWorld::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
if (!m_bSpriteBPressed)
{
return;
}
CCPoint touchLocation = touch->locationInView( touch->view() );
CCPoint prevLocation = touch->previousLocationInView( touch->view() );
touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
prevLocation = CCDirector::sharedDirector()->convertToGL( prevLocation );
m_pSpriteA->setPosition(touchLocation);
}