点击时如何更改精灵图像

时间:2015-01-29 22:31:25

标签: c++ ios cocos2d-x cocos2d-x-3.0

我知道这可能是有史以来最容易回答的问题之一,但我已经做了一些搜索,似乎无法找到答案......如何更改精灵图像时用户在Cocos2d-x中点击它?

我所知道的唯一方法就是使用这样的菜单图像:

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

但是只会在用户点击图片时更改图片..即使他们放开按钮,我怎么能让它保持更改?

1 个答案:

答案 0 :(得分:3)

此代码不需要任何菜单/按钮/ ...而是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);

希望帮助