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

我在想,如果我的图像可以有一个运行时事件,如果满足某个条件,对象将触发其运行时事件。

myImage = display.newImage("MYIMAGE")

myImage:addEventListener("enterFrame", myImage)

myImage.occurence = onEventTriggered

我不确定这段代码是否有效,因为我当前的计算机上没有LUA / Corona。

点赞
用户869951
用户869951

enterFrame事件仅由Runtime提供,但在enterFrame处理程序中,您可以检查对象的状态并执行每帧所需的任何检查:

`` ` myImage = display.newImage("MYIMAGE") local function enterFrame(event) if myImage.y == 0 then -- 在一秒钟内将其移动到50,50 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 -- 在一秒钟内将其移动到50,50 local settings = { time = 1000, x = 50, y = 50 } transition.to( square, settings) end end -- 创建新图像: local newImage = display.newImage("MYIMAGE") table.insert(myImages,newImage) end

Runtime:addEventListener("enterFrame", enterFrame) `` `

请注意,如果对象属性上存在现有转换,则必须在启动新转换之前取消该转换。在这种情况下,您将把transition.to的返回值放在表中,并在启动新转换之前检查该表中是否有项目;如果是,则取消它并将其删除。

这个陷阱与转换相关的问题也适用于您在问题的另一个答案中解释的每个对象enterFrame事件。不同的是,使用每个对象enterFrame时,您不需要myImages表。但是,您需要在调用enterFrame之前创建对象,这不是全局enterFrame的情况。如果您在每个帧中生成对象,则需要全局enterFrame。另一方面,您可以同时使用两者:

`` ` local checkConditionPerObject(self,event)      if myImage.y == 0 then -- 在一秒钟内将其移动到50,50          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) `` `

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

2014-02-27 15:54:31
用户1870706
用户1870706

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

myObject = display.newImageRect("player.png",64, 64)
function myObject:doSomething()
   -- do stuff
end
Runtime:addEventListener("enterFrame", myObject)
2014-03-01 04:18:16