我正在尝试使用以下代码向从表中随机选取的图像添加触摸事件:
easyGame2 = function()
catTable = { 'catwhite', 'catblue', 'catred', 'catyellow', 'catgreen', 'catorange', 'catpink', 'catpurple'}
randomCat = catTable[math.random(#catTable)]
cat = display.newImageRect(randomCat..'.png', 50, 50)
cat.x = math.random(20, display.contentWidth-20)
cat.y = 0
cat.myName = randomCat
transition.to( cat, { rotation = cat.rotation-360, time=2000, y=500,
onComplete=easyGame2})
end
easyGame2()
cat:addEventListener('touch', tapCat )
tapCat = function(event)
if event.phase == 'began' then
score = score + 2
display.remove(cat)
cat = nil
end
end
它在第一次触摸时起作用,然后就好像不再有听众了。如何使其适用于 [math.random(#catTable)] 中选择的每个图像
我也试过这段代码:
local catTable = {}
cat1 = {}
cat1.imgpath = 'images/catwhite.png'
table.insert(catTable, cat1)
--cat1:addEventListener('touch', tapCat ) --causes errors
cat2 = {}
cat2.imgpath = 'images/catblue.png'
table.insert(catTable, cat2)
cat3 = {}
cat3.imgpath = 'images/catred.png'
table.insert(catTable, cat3)
cat4 = {}
cat4.imgpath = 'images/catyellow.png'
table.insert(catTable, cat4)
cat5 = {}
cat5.imgpath = 'images/catgreen.png'
table.insert(catTable, cat5)
cat6 = {}
cat6.imgpath = 'images/catorange.png'
table.insert(catTable, cat6)
cat7 = {}
cat7.imgpath = 'images/catpink.png'
table.insert(catTable, cat7)
cat8 = {}
cat8.imgpath = 'images/catpurple.png'
table.insert(catTable, cat8)
easyGame2 = function()
randomCat = catTable[math.random(#catTable)]
cat = display.newImageRect(randomCat.imgpath, 50, 50)
cat.x = math.random(20, display.contentWidth-20)
cat.y = 0
cat.myName = randomCat
transition.to( cat, { rotation = cat.rotation-360, time=2000, y=450, onComplete=function(self)self.parent:remove(self);self=nil;end})
for i = 1, #catTable do
catTable[i]:addEventListener('touch', tapCat)--causes error
end
end
这给出了错误“181:试图调用方法'addEventListener'(一个零值)