对生成的精灵的操作 cocos2d-x

Action on spawned sprites cocos2d-x

在我的代码中,我每 1.5 秒生成一个 sprite,但是当我触摸该 sprite 时,它​​只对最后一个生成的 sprite 起作用,我怎样才能让它与所有 sprites 一起工作?

我的代码:(不是全部)

void HelloWorld::spawnRedThing(float dt) {
//actions for spawning the sprite
}

bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
//actions on touching
}

bool HelloWorld::init()
{

//create touch listener
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

//create timer for spawning sprites 
this->schedule(schedule_selector(HelloWorld::spawnRedThing), 1.5);
}

在函数 onTouchBegan() 中你需要检查你生成的每个精灵,所以你需要将所有精灵设置到一个列表中,并检查它是否被触摸 我的代码是 lua:

local spriteList = {}
for index,obj in pairs(spriteList) then
    if cc.rectContainsPoint(obj:getBoundingBox(),touch.getLocation()) then
      --touched
    end
end

是的,它有效,spriteList 像这样在外面:

local spriteList = {}  
local function spawnRedThing(dt)
  local sprite = cc.Sprite:create("land.png")
  table.insert(spriteList,sprite)
end

local function touchBegan(touch,event)
  for index,obj in pairs(spriteList) do
    if cc.rectContainsPoint(obj:getBoundingBox(),touch:getLocation()) then
      --sprite touched
    end
  end
  return true
end