enterFrame 事件仅由运行时执行,但在 enterFrame 处理程序中,您可以检查对象的状态并在每一帧执行所需的任何检查:
myImage = display.newImage("MYIMAGE")
local function enterFrame(event)
if myImage.y == 0 then -- move it to 50, 50 in one second
local settings = { time=1000, x=50, y=50 }
transition.to( square, settings)
end
end
Runtime:addEventListener("enterFrame", enterFrame)
使用这种技术,enterFrame 和对象是独立的:enterFrame 将每帧调用一次,在其中您可以检查 enterFrame 函数可见的任何对象。如果您有一个对象表,您将遍历表内容。例如,
myImages = {}
local function enterFrame(event)
for i, image in ipairs(myImages) do
if myImage.y == 0 then -- move it to 50, 50 in one second
local settings = { time=1000, x=50, y=50 }
transition.to( square, settings)
end
end
-- create new images:
local newImage = display.newImage("MYIMAGE")
table.insert(myImages, newImage)
end
Runtime:addEventListener("enterFrame", enterFrame)
请注意,如果对象属性上存在现有转换,则必须在开始新转换之前取消该转换。在这种情况下,您可以将 transition.to 的返回值放入一个表中,并在开始新的转换之前检查该表中是否有项目;如果是,请取消并删除它。
如果您使用 Rob 在您的问题的另一个答案中解释的每个对象 enterFrame 事件,则此与转换相关的问题也适用。不同的是,使用每个对象的 enterFrame,您不需要 myImages 表。但是,您确实需要在调用 enterFrame 之前创建对象,这不是全局 enterFrame 的情况。如果你在每一帧都生成对象,那么你想要的是一个全局 enterFrame。 OTOH,您没有理由不能同时使用两者:
local checkConditionPerObject(self, event)
if myImage.y == 0 then -- move it to 50, 50 in one second
local settings = { time=1000, x=50, y=50 }
transition.to( self, settings)
end
end ...
local function spawn(event)
local newObject = display.newImage(...)
newObject.enterFrame = checkConditionPerObject
Runtime:addEventListener('enterFrame', newObject)
end
local function enterFrameGlobal(event)
if someCondition() then
spawn()
end
end
Runtime:addEventListener("enterFrame", enterFrameGlobal)
这提供了很好的关注点分离。