Help with resetting timer/spawn creation (solved)

Ok, I have everything working like I want. I want to be able to spawn objects from a plane that flies across the screen. So a factory creates the plane. Then another factory spawns my minions coming out of the plane. Right now I have it set to 3, but later I will adjust that as game inputs change. However, the issue is the pplane only creates objects while it’s the only plane GO. I have to wait until that one is deleted to spawn new minions from the plane. Here is the code I’m using.

go.property(“acceleration”, 200)
go.property(“max_speed”, 400)
go.property(“left_or_right”, 1)

local spawn_timer = nil
local numMinions = 3
local i = 1

function init(self)
– movement input
self.input = vmath.vector3()

-- the current direction of movement
self.direction = vmath.vector3()

-- the current speed (pixels/second)
self.speed = 1

--spawn minions  
i = 1
spawn_timer = timer.delay(.5, true, spawnMinion)
print("spawn timer started")

end

function update(self, dt)
self.input.x = self.left_or_right
self.direction = self.input
– increase speed
self.speed = self.speed + self.acceleration * dt
– cap speed
self.speed = math.min(self.speed, self.max_speed)

-- move the game object
local p = go.get_position()
p = p + self.direction * self.speed * dt
go.set_position(p)

-- reset input
self.input = vmath.vector3()

end

function spawnMinion(self)
local p = go.get_position()
local pos = vmath.vector3(p.x, p.y, 0)
if i <= numMinions then
local minion_id = factory.create("#minionfactory", pos, nil, nil, .5)
i= i+1
elseif i > numMinions then
timer.cancel(spawn_timer)
end
end

function on_message(self, message_id, message, sender)
– check for the message
if message_id == hash(“collision_response”) then
– delete plane gameobject when it hits out of bounds
go.delete()
end
end

function final(self)
– Cancel the timer when the script is deleted
timer.cancel(spawn_timer)
go.delete()
end

This script is attached to the plane game object, correct?

Not sure this will fix it, but I’d try moving your spawn_timer variable onto self, instead of being a top-level local variable. Seems worth a try.

3 Likes

Top-level variables share their value between every instance of the script, so in this case every plane will have the same spawn_timer, numMinions, and i. For things that should be unique per object, store them in self like you’ve done for self.speed.

4 Likes

Thank you so much! You nailed it.

1 Like