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 に、Ground 3 を Ground2 に、というように再割り当てし、最後に新しいタイルを作成してそれを Ground8 に割り当てます。

バックグラウンドスクロールで同様のことを行いましたが、正常に機能しています。ただし、このコードを実行しようとすると、しばらくは機能します (最初の 4 つのタイルが正常にスクロールされます) が、タイル 5 を Ground1 に割り当ててアニメーション プロセスに戻ろうとすると、次の例外が発生します。

フィールド 'x' (nil 値) で演算を実行しようとしました

何か案は?

4

1 に答える 1

2

ground6にシフトするのを忘れましたground5

私はコロナを知らないので、内部で何が行われるのかわかりませんremoveSelfが、オブジェクトを破壊したりx、有効なインデックスではなくなったメタテーブルを削除したりしていると思います。ground5オブジェクト参照をground4、、、、にコピーすると3、最終的にはこの方法で破棄され、その時点で戻り、表示された例外が発生します。21ground5.xnil


ヒント:番号(v1、v2、v3など)だけが異なる変数のリストを作成しないでください。それがアレイの目的です。地上画像を保持するための8つの変数ではなく、8つすべてを保持する1つの配列が必要です。次に、ループを使用して、すべての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 に答える