可以显示对象在LUA中有运行时事件吗?

时间:2014-02-27 07:53:24

标签: lua corona

我在想我的图片是否可以有运行时事件?喜欢

当应用程序正在运行时,如果满足某个条件,该对象将触发其运行时事件。

myImage = display.newImage("MYIMAGE")

myImage:addEventListener("enterFrame", myImage)

myImage.occurence = onEventTriggered

我不确定这段代码是否有用,我当前的电脑里没有LUA / Corona

2 个答案:

答案 0 :(得分:1)

enterFrame事件仅由Runtime执行,但在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和object是独立的:每帧调用一次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)

这提供了一个很好的关注点分离。

答案 1 :(得分:1)

您可以执行基于对象的enterFrames。它们仍然是Runtime对象的一部分,但它可以是表处理程序而不是函数处理程序:

myObject = display.newImageRect("player.png",64, 64)
function myObject:doSomething()
   -- do stuff
end
Runtime:addEventListener("enterFrame", myObject)