在尝试在Corona SDK中平铺地面时遇到异常。

我正在使用以下代码:

ground1.x = ground1.x - 10
   ground2.x = ground2.x - 10
   ground3.x = ground3.x - 10
   ground4.x = ground4.x - 10
   ground5.x = ground5.x - 10
   ground6.x = ground6.x - 10
   ground7.x = ground7.x - 10
   ground8.x = ground8.x - 10

   if(ground1.x < ( 0 - 75 ) ) then
          ground1:removeSelf()
          ground1 = ground2
          ground2 = ground3
          ground3 = ground4
          ground4 = ground5
          ground6 = ground7
          ground7 = ground8
          local num = math.random ( 1, 4 )
          ground8 = display.newImage( group, "normalground"..num..".png", ground7.x + ground7.contentWidth/2, display.contentHeight - 52 )

来制作动态地面。我使用了8个块,ground1-ground8。这段代码在我的“enterFrame”中调用了一个animate函数。

我的目标是当“ground1”移动到了左边缘,我会重新分配地砖ground2到ground1,ground3到ground2,依此类推,最后创建一个新的地砖并将其赋给ground8。

我之前做过类似的背景滚动,它一直在正常工作。但当我尝试运行这段代码时,它可以成功地滚动前4个地砖,但一旦它尝试将第5个地砖分配给ground1并通过动画过程,我会收到以下异常:

attempt to perform arithmetic on field 'x' (a nil value)

有任何想法吗?

点赞
用户501459
用户501459

你忘记将 ground6 下移至 ground5

我不了解 Corona,所以我不知道 removeSelf 在内部做了什么,但我猜它销毁了对象和/或删除了它的元表,使得 x 不再是有效索引。既然您将对象引用从 ground5 复制到 ground4321,则最终以这种方式将其销毁,此时 ground5.x 返回 nil,然后您会看到异常。


提示:您永远不应该拥有仅因编号不同而不同的变量列表(v1、v2、v3 等)。这就是数组的用途。与其拥有 8 个变量来保存地面图像,不如拥有一个数组,其中包含所有 8 个。然后,您可以使用循环执行操作,例如将它们全部移动 N 个像素。

例如,如果我们将您的 8 张图像放在名为 ground 的列表中(例如 ground = {ground1,ground2,ground3,ground4,ground5,ground6,ground7,ground8},尽管您可能不会以这种方式初始化它),则可以重写代码:

-- 将地面向右平移 10 个像素
for i,tile in pairs(ground) do
  tile.x = tile.x - 10
end

if ground[1].x < (0 - 75) then
  -- 移除第一个瓷砖
  ground[1]:removeSelf()
  for i=1,#ground-1 do
    ground[i] = ground[i+1]
  end
  -- 在末尾添加一个新的瓷砖
  local num = math.random ( 1, 4 )
  ground[#ground] = display.newImage( group, "normalground"..num..".png", ground[#ground-1].x + ground[#ground-1].contentWidth/2, display.contentHeight - 52 )
end

代码更精简,即使您将 10 个地面砖块移动到 100 个,也无需更改,并避免了您在 OP 中所犯的错误。

2012-06-06 05:11:46