【问题标题】:Make two objects touchable which were created with a function (LUA, Corona)使两个使用函数(LUA,Corona)创建的对象可触摸
【发布时间】:2013-02-10 19:49:54
【问题描述】:

我猜这是一个真正的新手问题,

但我有以下代码:

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)

我把它清理了一下,专注于重要的事情。

我现在的问题是:我可以触摸一个圆圈并对其进行缩放。但这仅适用于其中一个圆圈(我想创建 3 或 4 个)。而且我猜它只适用于创建的最后一个圈子。

我想这里的主要问题是,我用“createCircle()”创建的所有圆圈都被命名为“圆圈”。所以 evenListener 只适用于我创建的“圈子”。

有什么想法可以选择我创建的其他圈子吗?

谢谢你:)

【问题讨论】:

    标签: function lua coronasdk addeventlistener


    【解决方案1】:

    必须使用表格。例如:

    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
    

    【讨论】:

    • 感谢您的回答。我会试试的。
    • 我阅读了一些关于表格的教程。您的解决方案似乎是要走的路,但我仍然有一个问题:“function circle:touch(event)”给我一个错误,因为“circle”没有真正定义。我怎样才能绕过它?我现在在这个问题上编码了几个小时:/
    • 正确:“尝试索引全局 'circle' (a nil value)”是我得到的错误消息。
    【解决方案2】:

    我就是这样解决的:

    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()
    

    我猜 Dream Eaters 解决方案也应该可以。但是我在调​​用 createCircle() 函数时又犯了一个错误。我通过为 TouchListeners 创建一个函数并在 createCircle() 函数之后调用它来解决这个问题。

    希望这可以帮助其他有类似问题的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      相关资源
      最近更新 更多