Having read your posts on other threads, you seem to be having issues with how you refer to objects in your code.
It is important to understand that if you create two objects that have the same name, then you will lose reference to the first object. For instance,
local object = display.newRect( 100, 100, 100, 100 )
object.name = "object 1"
local object = display.newRect( 200, 100, 100, 100 )
object.name = "object 2"
print (object.name ) -- prints "object 2"
However, since you didn’t remove the first object before you created the new one, so it still exists. You just can’t access it easily. The way how @roaminggamer creates enemies in his code is good because it will add the new enemies to a table where you can always access them and easily remove them.
Now, in your conditional checks and zombieCollision
listener, you are checking for zombie
. This means that if you ever have more than a single object named zombie
in your game, then your conditional checks and collisions listener simply won’t work.
You need to design your code in a way that it will work for all objects, not just for objects with a singular reference. For instance, in your collision listener, you have self
and other
. So write your listener in a way that it works for the two objects that are colliding, regardless of what their names/references are.
Also, you need to pay attention to how you remove display objects.
if zombie.removeSelf then
zombie.x = zombie.x + 2
end
This check isn’t good. If that’s all there is to it, then it may crash if zombie
is nil because it is trying to access an entry within a table, but if there is no table to start out with, it’ll just crash.
If you would instead check for
if zombie then
zombie.x = zombie.x + 2
end
Then, if you are sure that zombie
can ever be used for a display object, you’d be safe from crashes for the check itself. Furthermore, if you only ever use it for display objects, then we know that if zombie
exists, then it’s table entries will as well (unless you’ve somehow explicitly removed them without removing the table itself).