在Corona中,EnterFrame事件会提前停止。

我想要通过增加1来扩展我的矩形的宽度,并希望它在达到屏幕宽度时停止。然而,在我的代码中,它在屏幕中间停止增加。请问我缺少了什么?

W = display.contentWidth
H = display.contentHeight

local rect = display.newRect(0, 0, 0, 100)
rect:setFillColor(0, 255, 0)

local function expand()
  rect.width = rect.width + 1
  print(rect.width)
  if rect.width == W then
    Runtime:removeEventListener("enterFrame", expand)
  end
end

Runtime:addEventListener("enterFrame", expand)
点赞
用户2040431
用户2040431
W = display.contentWidth
H = display.contentHeight

local rect = display.newRect(0, 0, 0, 100)
rect:setFillColor(0, 255, 0)

local function expand()
    rect.width = rect.width + 1
    rect.x = 0
    print(rect.width)
    if rect.width == W then
        Runtime:removeEventListener("enterFrame", expand)
    end
end

Runtime:addEventListener("enterFrame", expand)

在 Corona 中,所有视图默认都有左上角的参考点。这意味着,如果你把它们放在 (0,0,0,100) 的位置,它们将从左上角开始,并具有 100 像素的高度。视图(在这个例子中是 rect)的 x 值将位于其左侧。

增加这个矩形的宽度不会改变矩形的位置,只会让它变宽。因此,在宽度增加的一半处,会在屏幕之外找到它的左侧。

2013-06-15 23:54:38
用户1979583
用户1979583

你可以通过在代码开头添加rect.x=W/2来了解代码中发生了什么,如下所示:

W=display.contentWidth
H=display.contentHeight

local rect = display.newRect(0,0,0,100)
rect:setFillColor(0,255,0)
rect.x = W/2          -- 将此代码添加到您的代码中,查看实际效果

local function expand()
    rect.width= rect.width+1
    print(rect.width)
    if rect.width==W then
      Runtime :removeEventListener("enterFrame", expand)
    end
end
Runtime: addEventListener("enterFrame", expand)

现在,您可以使用以下代码解决此问题(我使用了一个名为incrementVal的变量,仅供您方便,以了解rect大小和位置之间的关系):

W=display.contentWidth
H=display.contentHeight

local rect = display.newRect(0,0,0,100)
rect:setFillColor(0,255,0)

local incrementVal = 1
local function expand()
  rect.width= rect.width+incrementVal
  rect.x = rect.x + (incrementVal/2)  -- 添加的额外代码,用于正确工作
  if rect.width==W then
    Runtime :removeEventListener("enterFrame", expand)
  end
end
Runtime: addEventListener("enterFrame", expand)

继续编码…… :)

2013-06-16 17:46:46