ammo[#ammo + 1] = { <-- this is like a counter to put in table ammo +1?
x = playerX, <-- put the bullet in the same coordinates as the player?
y = playerY
I'm sorry for this silly questions but i' a n00b to game programming.
for i = 1, #ammo do
ammo[i].x = ammo[i].x + (dt * 300)
end
If you declare ammo = {}, isn't this an empty table? how can i have as enemys as i want?
Correct, it's an empty table, or in other words, a table with 0 entries. So that loop will happen a total of 0 times. If we had, say, 5 entries in the table, the loop would happen 5 times. If we had 500 entries, it would happen 500 times. The beauty of #ammo is that we can stick it in and then not worry about it.
To have as many enemies as you want, just extend the concepts we're using for ammo to the enemies.
ammo = {} -- 0 entries
ammo = { -- 1 entry
"string"
}
ammo = { -- 2 entries
"string",
1
}
Taking it a step further, entries don't have to be strings or numbers. They can also be tables (each table counts as one entry, regardless of how many entries it has). Like this:
The code that I posted (in love.keypressed) inserts a table into the ammo table. The subtable contains the values for each bullet: in this case, just an X/Y coordinates. The for loops use those subtable values for updating: ammo.x refers to the X value of whichever subtable you are currently on in the for loop.
is the part that is responsable for increase the number of items inside the table wright?
Yes, it's part of it.
cvirus wrote:
So I have to do the same at my var maxEnemies i think.
Not... quite. Replace #maxEnemies with #enemy, and pass a parameter into posEnemy to control how many enemies you want to create and position. Here, attached is what I mean. I also adjusted a few other little things.
for i = 1, #ammo do
ammo[i].x = ammo[i].x + (dt * 300)
end
I have this code and to clear the items inside so the table doesn t get to big and slow i must clear those items as soon as they get off the screen, right?
instead of ammo i changed to shot, and this works if only i shot once at a time and let the bullet get off the screen, but if i shot more times in a row then it gives an error saying.
for i = 1, #shot do
shot[i].y = shot[i].y + 2 <---- here is when it says that message
if shot[i].y > 480 then
shot[i].visible = false
table.remove(shot)
end
end
for i = 1, #shot do
shot[i].y = shot[i].y + 2
if shot[i].y > 480 then
shot[i].visible = false
end
end
for i = #shot, 1, -1 do --traverse backwards to remove items without everything going to hell
if not shot[i].visible then
table.remove(shot, i)
end
end
In this case you might replace it by a single backwards loop. Anyway, this is a tricky thing you always need to keep in minds whenever you remove things in a loop.