0

我正在使用以下代码:

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”上调用。

我要做的是检测“ground1”何时离开左边缘。然后,我将地块ground2 重新分配给ground1,将地块3 重新分配给ground2,以此类推,最后,创建一个新地块并将其分配给ground8。

我对背景滚动做了类似的事情,效果很好。但是,当我尝试运行此代码时,它工作了一段时间(它成功滚动了前 4 个图块)但是一旦它尝试将图块 5 分配给 ground1 并返回动画过程,我得到以下异常:

尝试对字段“x”(零值)执行算术运算

有任何想法吗?

4

1 回答 1

2

你忘了切换ground6到 down to ground5

我不知道 Corona,所以我不知道removeSelf内部做什么,但我猜它会破坏对象和/或删除它的元表,从而x不再是有效的索引。由于您将对象引用复制ground5ground4, 那么3, 21它最终会以这种方式被销毁,此时ground5.x返回nil并且您会看到您看到的异常。


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

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

-- shift the ground 10 pixels to the right
for i,tile in pairs(ground) do
  tile.x = tile.x - 10
end

if ground[1].x < (0 - 75) then
  -- shift out the first tile
  ground[1]:removeSelf()              
  for i=1,#ground-1 do
    ground[i] = ground[i+1]
  end
  -- add a new tile to the 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-06T05:11:46.283 回答