Touch sprites which are elements of a ScrollView

I’ve been through the forum searching for an example of detecting touches on a specific sprite element of a ScrollView but I was unlucky to find one. Here is my ScrollView with sprites as elements:

ScrollView* scrollMenu = ScrollView::create();
    scrollMenu->setDirection(ScrollView::Direction::HORIZONTAL);
    scrollMenu->setContentSize(Size(visibleSize.width, 600));
    scrollMenu->setInnerContainerSize(Size(visibleSize.width * 2.14f, 600));
    scrollMenu->setAnchorPoint(Vec2(0.5f, 0.5f));
    scrollMenu->setBounceEnabled(true);
    scrollMenu->setScrollBarEnabled(false);
    scrollMenu->setInertiaScrollEnabled(true);
    scrollMenu->setPosition(Vec2(background->getContentSize().width / 2, background->getContentSize().height / 2));

    for(unsigned short int say = 0; say < 8; say++)
    {
        std::stringstream fileName;
        fileName.str(std::string());
        fileName << "level-" << say + 3 << "-selection.png";
        auto scrollElems = Sprite::create(fileName.str());
        scrollElems->setName("level");
        scrollElems->setPosition(Vec2((195 + (say * 385)), scrollMenu->getContentSize().height / 2));
        scrollMenu->addChild(scrollElems,2);
    }

So how to do it?

depends what you want to do with the sprite. but you may searchign for ImageView widget

take a look here : http://www.cocos2d-x.org/reference/native-cpp/V3.5/df/d0b/classcocos2d_1_1ui_1_1_image_view.html

Thank you for your response but i need a ScrollView with a bounch of Sprites as elements. And when an element(Sprite) of the ScrollView is clicked(lets say the second sprite), I need to detect that the second sprite is clicked.

1 Like

this is what I suggested. you can use an ImageView per sprite and it will automaticlly have a touch event handler.

Okay show me the touch example with ScrolView+TouchView elements.

ImageView is based on a Widget so you should have the same API just as you have to a button.

Create your ImageView using

auto image = ImageView::create(“pngfile.png”);

with image you can do whatever you are used to with widget and Node such as SetPosition and addChild.

do :
image->setTouchEnabled(true);
and add
image->addTouchEventListener(…) to register for your touch callback. and you are done…

If you don’t understand . search for cocos2dx::ui::Button examples which is exactly the same but instead of a button a static image.

Is it possible to add event listeners to the sprites which are the elements of ScrollView and then later detect touches on them by the way? I’ll give it a try. Thank you.

Sprites does not have a touch event handler. if you wish to detect it over sprite you will need to make the calculation yourself (not that complicated) using the boundingBox of your sprite based on the touch coordinaes.

But ImageView is doing all the dirty work for you already. It is the right way to do it for your case I assume.