-1

我正在尝试使用以下代码向从表中随机选取的图像添加触摸事件:

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'(一个零值)

4

2 回答 2

0

像这样将您的 tapcat 函数放在侦听器上方的任何位置

tapCat = function(event)
if event.phase == 'began' then
    score = score + 2
    display.remove(cat)
    cat = nil
   end  
end

cat:addEventListener('touch', tapCat )
于 2013-06-21T23:11:31.710 回答
0

没关系,我设法通过进行以下编辑来解决它:

randomCat = catTable[math.random(#catTable)]
cat = display.newImageRect(randomCat..'.png', 50, 50)
transition.to( cat, { rotation = cat.rotation-360, time=2000, y=500,onComplete=easyGame2}) 

randomCat = math.random(#catTable)
cat = display.newImageRect(catTable[randomCat], 50, 50)
cat.type = randomCat
cat.trans = transition.to( cat, { rotation = cat.rotation-360, time=2000, y=550, onComplete=function(self)self.parent:remove(self);self=nil;end})
cat:addEventListener('touch', tapCat )
return cat
end

tapCat = function(event)
    catTouch = event.target
    transition.cancel (event.target.trans)

    if catTouch.type == catnormal then
        score = score + 5
    else 
        score = score + 10
    end
        display.remove(catTouch)
        cat = nil
    return true
end

感谢 Vovahost 的回答。

于 2013-06-22T16:48:19.243 回答