如何在Corona SDK中使我的传感器正常工作?

以下是代码:

local bottombar = display.newLine(0, 480, 340, 480)
physics.addBody(bottombar, "static", {isSensor = true})

function bottombar:collision(event)
    if(event.phase == "began") then
        a = a + 1
        print(a)

        if(a == 4) then
            timer.cancel(timer1)
            storyboard.gotoScene("scene_results")
        end
    end
end

bottombar:addEventListener("collision", bottombar)

end

这个游戏会生成掉落的水滴,当有3个水滴穿过底线时,我想停止游戏。变量'a'最初为0,当第一个水滴穿过底线时,控制台中的'a'将是1,当第二个水滴穿过底线时,控制台会显示'a'是2,并显示在下一行3,就像这样:

1 => 第一个水滴
2   }
    }=> 第二个水滴
3   }

如果我将第一个水滴的if(a == 10)更改,在第二个水滴时,'a'为(2, 3),在第3个时为(4, 5, 6),当第4个水滴穿过线时,'a'为(7, 8, 9, 10)。

或者,如果我摧毁3个水滴(self:removeSelf() 当我碰到它们时),并让第4个水滴穿过线,则'a'变成:

1
2
3
4

如果表达不清楚,我很抱歉。

这是整个代码,我想不出我错在哪里了:

local a = 0
local score = 0

local function game()
    local pop = audio.loadSound("pop.WAV")
    local masterVolume = audio.getVolume()

    local function createCircle()
        function onCircleTouch(self, event)
            if(event.phase == "began") then
                timer.performWithDelay(1, function()
                    self:removeSelf()
                    audio.play(pop,{channel=0,loops=0})
                    score=score+10
                    globals.score = score
                end )
            end
            return true
        end
        local circle = display.newImage("ballon2.png",math.random(10,300),0)
        physics.addBody( circle, "dynamic", { desity=1.0,friction=0 })
        circle.touch = onCircleTouch
        circle:addEventListener("touch", circle)
    end

    local function balls(event)
        createCircle()
        local bottombar=display.newLine(0, 480, 340, 480)
        physics.addBody(bottombar, "static" ,{isSensor=true})
        function bottombar:collision(event)
            if(event.phase == "began") then
                a=a+1
                print (a, event.other)
                if( a == 3) then
                    timer.cancel(timer1)
                    storyboard.gotoScene( "scene_results" )
                end
            end
        end
        bottombar:addEventListener("collision", bottombar)
    end

    timer1=timer.performWithDelay( 1000, balls, 0 )
end

game()
点赞
用户869951
用户869951

我无法重现这个问题:我拿了你发布的代码,创建了三个按钮并将它们作为动态对象添加到物理系统中,然后让它们朝着那条线掉落。我每个物体都得到了一个输出结果。问题可能出现在你的代码的其他地方。你能否创建一个最小化的独立例子,这样可能会显露出问题所在。

请检查以下事项:

1.验证你是否在碰撞事件期间移除了碰撞的球。必须延迟移除。 2.将打印更改为 print(a, event.other),以查看其他碰撞是否涉及不同的球体,这将表明物理引擎仍在演化已通过该线的球体上。

关于样式的说明:Lua 不需要在 if 条件周围加上 ()() 是多余的,只会增加噪音。

2014-04-09 03:50:57
用户2201706
用户2201706

最终我找到了解决我的问题的方法。我在 local score = 0 下面放置了以下代码:

local bottombar=display.newLine(0, 480, 340, 480)
physics.addBody(bottombar, "static" ,{isSensor=true})

然后我在这个代码下面添加了 bottombar:addEventListener("collision", bottombar)

2014-04-15 15:45:57