【问题标题】:EnterFrame event stops early in CoronaEnterFrame 事件在 Corona 中提前停止
【发布时间】:2013-06-11 23:12:41
【问题描述】:

我想将矩形的宽度增加 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)

【问题讨论】:

    标签: lua coronasdk enterframeevent


    【解决方案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
          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 像素。视图的 x 值(在这种情况下为矩形)将位于其左侧。

    增加这个矩形的宽度不会改变矩形的位置。只是让它更宽。因此,宽度增加的一半出现在屏幕之外,在这种情况下位于左侧。

    【讨论】:

    • 现在,这完全有道理。谢谢你的启发。 =)
    【解决方案2】:

    您可以通过将 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          -- just put this in your code and see what actually happening
    
    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 的变量,只是为了您的方便,以了解代码中矩形大小和位置的关系):

    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)  -- additional line, added for proper working
      if rect.width==W then
        Runtime :removeEventListener("enterFrame", expand)
      end
    end
    Runtime: addEventListener("enterFrame", expand)
    

    继续编码........ :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 2022-12-18
      • 2018-02-27
      • 1970-01-01
      • 2016-04-09
      相关资源
      最近更新 更多