Reputation: 380
I am working on a small zombie game, I would like to spawn zombies randomly and keep track of them so if they collide with a bullet object then they are removed however if they collide with the hero then they attack.
I get the logic to remove them or make them attack on collision, however I am not sure how to randomly spawn multiple objects on screen and keep track of them.
I am not asking for anyone to write code for me, just need guidance on the task.
Thanks in advance.
Upvotes: 0
Views: 438
Reputation: 805
What you can do is get the display.viewableContentWidth and display.contentHeight (varies depending on your config.lua, you can view more here).
First set math.randomSeed(os.time) on the main.lua file REASON is we want to a different random everytime we open the app. you can view more here.
Second Store the values of display.viewableContentWidth and display.contentHeight on a variable lets say x and y and create a table namely zombies and a counter
Third Create a function that will be called everytime you want to spawn the zombies like:
local x = display.contentWidth
local y = display.contentHeight
local zombies = {}
local zombieCounter = 0
showZombies = function()
--Gives a value from 1 to x
local xVal = math.random(x)
--Gives a value from 1 to y
local yVal = math.random(y)
--spawn your zombie
zombies[zombieCounter] = display.newImageRect ("yourZombie.png", 70,90)
zombies[zombieCounter].x = xVal
zombies[zombieCounter].y = yVal
--set a tag for this zombie namely "myName"
zombies[zombieCounter].myName = zombieCounter
zombieCounter = zombieCounter + 1
end
fourth on your collision function (assuming you have all the listeners in)
zombieCollision = function(event)
--DO WHAT YOU NEED TO DO WITH YOUR ZOMBIE
--CALL THE COLLIDED ZOMBIE
local zombieNUmber = event.other.myName
print("The number of the zombie is "..zombies[zombieNumber].myName)
end
The trick here to track the zombies is the zombies[zombieNumber].myName inside your collision function.
Upvotes: 1