I’m using the following code:
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 )
to animate a moving ground. I’m using 8 tiles, ground1-ground8. This code is inside my animate function that is called on “enterFrame”.
What I’m trying to do is detect when “ground1” has moved off the left edge. Then, I’m reassigning the tile ground2 to ground1, ground 3 to ground2, etc, and at the end, creating a new tile and assigning it to ground8.
I did something similar with my background scrolling, which is working fine. However, when I try to run this code, it works for a while (it scrolls the first 4 tiles successfully) but once it tries to assign tile 5 to ground1 and go back through the animation process, I get the following exception:
attempt to perform arithmetic on field ‘x’ (a nil value)
Any ideas?
You forgot to shift
ground6to down toground5.I don’t know Corona so I don’t know what
removeSelfdoes internally, but I’m guessing it destroys the object and/or removes it’s metatable such thatxis no longer a valid index. Since you copy the object reference inground5toground4, then3,2,1, it eventually gets destroy in this way, at which pointground5.xreturnsniland you get the exception you saw.Tip: you should never have lists of variables that differ only by number (v1,v2,v3,etc.). That’s what arrays are for. Rather than have 8 variables to hold ground images, you should have one array that holds all 8. Then you can use loops to perform operations like shifting them all N pixels.
For example, if we had your 8 images in a list
ground(likeground = {ground1,ground2,ground3,ground4,ground5,ground6,ground7,ground8}, though you probably wouldn’t initialize it that way), you could rewrite your code:The code is more succinct, doesn’t need to be changed if you shift to 10 ground tiles or 100, and avoids errors like the one you made in your OP.