Corona - 在表格对象中使用触摸事件?

我正在尝试在一个项目中使用这个代码,但我不知道如何给转盘中的每个图标/对象添加触摸事件监听器,如果有人能提供一种快速的解决方法,我将不胜感激。

    local NUM_ITEMS=20;
    local radiusX= 200;
    local radiusY= 40;
    local centerX = 240;
    local centerY = 160;
    local speed = 0.05;
    local perspective = 3;

    local carousel = display.newGroup()
    local icons = {}

    local function zSort(myTable, myGroup)

            table.sort(myTable,
                    function(a, b)
                        return a.depth < b.depth -- depth is your custom field
                    end
            )
            for i = 1, #myTable do
                    myGroup:insert(myTable[i].img)
            end

    end

function Icon(i)
        local this = {}
        local icon = display.newImage(carousel, "images/icon"..i..".png")
        this.angle = (i-1) * math.rad(360/NUM_ITEMS);
        this.img = icon
        return this
end

function update(event)

        local icon
        local sin = math.sin
        local cos = math.cos

        for i=1, NUM_ITEMS, 1 do

                icon = icons[i]
                local img = icon.img

                img.x = cos(icon.angle) * radiusX + centerX
                img.y = sin(icon.angle) * radiusY + centerY

                local s = (img.y - perspective) / (centerX + radiusY - perspective)
                img.xScale = s*0.25
                img.yScale = s*0.25

                icon.angle = (icon.angle  + speed) --%math.rad(360)

                icon.depth = s

        end

        zSort(icons, carousel)

end

for i=1, NUM_ITEMS, 1 do
        local icon = Icon(i)
        icons[i] = icon
end

function onTouch(event)
        if(event.phase=="moved") then
                speed = (event.x - centerX) / 2000;
        end
end

Runtime:addEventListener("enterFrame",update)
Runtime:addEventListener("touch", onTouch)
点赞
用户1979583
用户1979583

我无法确定你具体需要的是什么。但是,如果你想为 localGroup 中的所有相同图标添加个性化标记,那么你可以将它们添加为图标数组,并给每个图标添加 specific tag,然后为它们添加个性化的响应方法,如下所示:

local icons = {}
for i=1,10 do
  icons[i] = display.newImage(i..".png")
  icons[i].tag = i
end

local function touchIt(e)
  print(e.target.tag)
  --[[ icons[e.target.tag] 可以用来识别并设置被点击图标的属性 --]]
end
for i=1,10 do
  icons[i]:addEventListener("touch",touchIt)
end

或者

如果你想将所有分组元素统一标记并触发响应,那么可以为所有图标赋予相同的标记或者添加 userdata 标记,以及为所有分组元素添加相同的触摸响应操作(如下所示)。

local icons = {}
for i=1,10 do
  icons[i] = display.newImage(i..".png")
  icons[i].tag = 1 --[[你也可以使用 icons[i].userdata = "icons"
                          (或任何字符串)--]]
end

local function touchIt(e)
  print(e.target.tag) -- 对于所有图标,它的值都是1
                      --[[ icons[e.target.tag] 可以用于识别
                           是否属于 'icons' 分组 --]]

  --[[ 或可使用 userdata,如下 --]]
  print(e.target.userdata) --[[输出是一个字符串,
                                用于表示分组/元素标识--]]
end
for i=1,10 do
  icons[i]:addEventListener("touch",touchIt)
end
2013-03-12 05:00:54