获取CCScrollview中触摸的位置

Getting position of a touch in a CCScrollview

本文关键字:位置 触摸 CCScrollview 获取      更新时间:2023-10-16

我在屏幕一侧有一个充满CCSprites的滚动视图,我希望能够将其中一个拖动到屏幕的主区域。我只需要找到用户开始拖拽的精灵。

我试着将触摸位置移动到每个精灵的坐标空间,但是数字到处都是。

位置为Touch->getStartLocationInView()

ScrollViewItems是Vector<Sprite*>

string HelloWorld::SpriteNameForPosition(cocos2d::Vec2* position)
{
for(Vector<Sprite*>::iterator iter = scrollViewItems.begin() ;iter !=  scrollViewItems.end();iter++)
{
    Sprite* sprite = *iter;
    Vec2 spriteTouchPos = sprite->convertToNodeSpace(*position);
    Rect bounds = Rect(0, 0, sprite->getBoundingBox().size.width, sprite->getBoundingBox().size.height);
    if(bounds.containsPoint(spriteTouchPos))
    {
        return names[sprite->getTag()];
    }
}
return "";
}

第一个问题是为什么要改变boundingBox的位置?而不是将你的位置设置为(0,0),只需获取boundingBox并检查该点是否包含在其中。

滚动视图将更新到内容/boundingBox的实际位置时,偏移量应用于所有子框,所以边界框将始终反映正确的位置,因为你在屏幕上看到。你可以通过使用drawNode在精灵周围绘制矩形来检查这一点。我通常将此作为调试的一种方式,以确保我正在使用正确的尺寸和位置。

你可以通过使用boundingBox来修复你的问题,因为它是从每个scrollViewItem返回的。

auto bounds = sprite->getBoundingBox();
if(bounds.containsPoint(position))
{
   return sprite->getName();
}