如何防止我的代码逻辑在 Corona 中不断增加分数

How can I keep my code logic from continuously increasing a score in Corona

下面的代码应该在箱子落在容器边界内时将分数加 1。

local score = 0
local thescore =  display.newText("Score " .. score,  150,430, native.systemFont , 19)
local function update()
    if (crate.x > side1.x and crate.x < side2.x and crate.y < shelf.y and crate.y > shelf.y - 50) then
            score = score + 1
            thescore.text = "Score " .. score
    end
end
timer.performWithDelay(1, update, -1)

我如何才能做到每次板条箱进入容器而不是它在容器内停留的每一毫秒都只给分数加 1一次

状态变量

使用一个变量来存储箱子的状态。当第一次在容器边界内找到它时,将变量设置为 true 并增加分数。下次调用 update() 时,如果该变量设置为 true,则分数不会改变。另一方面,如果在容器外发现了板条箱,则将变量设置为 false。它看起来像(伪代码):

local score = 0
local alreadyContained = false

local function update() 
    if crateIsInContainer() then
        if alreadyContained == false then
             alreadyContained = true
             score = score + 1
        end
    else
        alreadyContained = false
    end
end
timer.performWithDelay( 20, update )

顺便说一下,pointless 比帧的持续时间更频繁地调用您的更新函数。如果您的 config.luafps = 60 那么那是每 17 毫秒左右一帧。

使用物理学

这对您的游戏来说可能有点矫枉过正,但是对于物理,您可以使用物理体作为传感器并对重叠的不同阶段做出响应。这是documented here,我引用:

Any body — or any specific element of a multi-element body — can be turned into a sensor. Sensors do not physically interact with other bodies, but they produce collision events when other bodies pass through them....Objects that collide with a sensor will trigger a "began" event phase, just like normal non-sensor objects, and they will also trigger an "ended" event phase when they exit the collision bounds of the sensor.

另外请记住,这种物理体的使用检测的是重叠而不是包含,这似乎是您感兴趣的。