Search code examples
c++ioscocos2d-xcocos2d-x-3.0

How To Change A Sprite Image When Tapped


I know this is probably one of the easiest questions ever to answer, but I've done some searching and can't seem to find the answer to this... How do I change a sprites image when the user taps on it in Cocos2d-x?

The only way I know of is using a menu image like this:

auto box = MenuItemImage::create("box_untapped.png", "box_tapped.png");

but that only changes the image while the user is tapping it.. how do I get it to stay changed even after they let go of the button?


Solution

  • This code do not need any menu/button/... but a Touch Listener :

    auto mySprite = Sprite("A.png");
    
    auto touchListener = EventListenerTouchOneByOne::create();
        ///
    touchListener->onTouchBegan = [=](Touch* touch, Event* event){
        auto target = static_cast<Sprite*>(event->getCurrentTarget());
        Point locationInNode = target->convertToNodeSpace(touch->getLocation());
        Size s = target->getContentSize();
        Rect rect = Rect(0, 0, s.width, s.height);
        if (rect.containsPoint(locationInNode))
        {
            mySprite->setTexture("B.png"); // Here
            return true;
        }
        return false;
    };
    
    touchListener->onTouchEnded(Touch* touch, Event* event)
    {
        mySprite->setTexture("B.png"); // Or Here
    }
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, mySprite);
    

    Hope helps