Make two objects touchable which were created with a function (LUA, Corona)

ぃ、小莉子 提交于 2019-12-07 15:34:26

问题


I gues this is a real newbie question,

but I have the following code:

local function createCircle()
[...]
circle = display.newCircle( positionX, positionY, circleRadius )
[...]
end

function circle:touch( event )
   if event.phase == "ended" then
      scaleCircle(self,scaleUp)
   end
   return true;
end
circle:addEventListener("touch", circle)

I cleaned it up a bit, to concentrate on the important things.

My problem right now is: I can touch one circle and scale it. But this works only for one of the circles (I want to create like 3 or 4 of them). And I guess it only works for the last circle which was created.

I guess the main problem here is, that all circles I create with "createCircle()" are named "circle". So the evenListener only works for the "circle" I created.

Any ideas how I can select the other circles I created?

thank you :)


回答1:


You MUST use tables. For eg.:

circles = {}
local function createCircle()
  --[[ MORE CODE ]]--
  table.insert( circles, display.newCircle( positionX, positionY, circleRadius ) )
  --[[ MORE CODE ]]--
end
function circle:touch( event )
   if event.phase == "ended" then
      scaleCircle(self,scaleUp)
   end
   return true;
end
for _, circle in ipairs( circles ) do
  circle:addEventListener("touch", circle)
end



回答2:


This is how I solved it:

local function createCircle()
  --[[ MORE CODE ]]--
   table.insert(circleTable, display.newCircle( positionX, positionY, circleRadius ) )
   --[[ MORE CODE ]]--
end

function onObjectTouch(event)
   local self = event.target
   if event.phase == "ended" then
        --[[ MORE CODE ]]--
   end
   return true;
end

local function addTouchListeners()
   for _, circle in ipairs(circleTable) do
      circle:addEventListener("touch", onObjectTouch)
   end
end

createCircle()
addTouchListeners()

I guess Dream Eaters solution should work as well. But I had another mistake in calling my createCircle() function. I solved this with creating a function for the TouchListeners and call it AFTER the createCircle() function.

Hope this helps other people with similar problems.



来源:https://stackoverflow.com/questions/15070860/make-two-objects-touchable-which-were-created-with-a-function-lua-corona

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!