0
\$\begingroup\$

I'm trying to allow a CCSprite to be dragged across the screen. I've succeeded so far by doing it on a Layer level (from this tutorial). However, this only allows ONE sprite to be dragged at a time as the method implementation can only identify a single sprite to move at a time.

I'd like to be able to perhaps add a gesture recognizer or somehow implement ccTouchesBegan/Moved in my own little CCSprite subclass.

However, from what I understand, you can't just add gesture recognizers to CCSprites. ccTouchMoved are also not available on CCSprites?? Really confused as to how to implement touches on Cocos2D.

What is the easiest way to add some position translation code to a CCSprite so it can be dragged around? Thanks!

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

My logic here is that a Scene or Layer can need to act differently for the touch events depending upon what was touched.

So on the touch begin if you did indeed touch the sprite in question, I set a boolean.

On the touch end if that boolean is true, you take the point at where you dropped the sprite, check to see if the sprite is indeed contained in the spot you stopped the touch event and then set that as the new position for the sprite.

Something like:

bool GameScene::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    CCPoint touchLocation = touch->getLocationInView();
    touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );

    CCRect meatboyBounds = meatboy->boundingBox();

    if(meatboyBounds.containsPoint(touchLocation))
    {
        m_bSpriteBPressed = true;
    }

    return true;
}

void GameScene::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
    if (m_bSpriteBPressed)
    {
        CCPoint touchLocation = touch->getLocationInView();
        touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
        m_bSpriteBPressed = false;
        meatboy->setPosition(touchLocation);
    }

}
\$\endgroup\$
0
0
\$\begingroup\$

Hmm...not sure if this will help you.

I've actually created my own abstraction of the CCTouchDispatcher and subclassed CCSprite. Through that dispatcher, I register all my sprites/layers/etc. Since the dispatcher can do all the cocos2d touch events, I can send message to those sprites.

I'm fond of subclassing cocos2d classes so that it'll fit to my needs and make the development faster.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .