Reputation: 191
Below is code that is supposed to add 1 to the score when the crate lands within the boundaries of a container.
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)
How do I make it so that it only adds 1 to the score once each time the crate enters the container and not for every millisecond it stays inside the container?
Upvotes: 1
Views: 50
Reputation: 1183
Use a variable to store the status of the crate. When it is first found within the boundaries of the container, set the variable to true
and increase the score. The next time update()
is called, if that variable is set to true the score is not changed. If, on the other hand, the crate is found outside the container, set the variable to false
. It would look like (in pseudocode):
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 )
By the way, it is pointless to call your update function more frequently than the duration of a frame. If your config.lua
has fps = 60
then that's one frame every 17 ms or so.
This might be overkill for your game, but with physics you can use physics bodies as sensors and respond to different phases of the overlap. This is documented here, and I quote:
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.
Also keep in mind that this use of physics bodies detects overlap rather than containment, which is what you seem to be interested in.
Upvotes: 2