Enemy spawnage

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
Mr. Russian
Prole
Posts: 1
Joined: Thu Apr 03, 2014 10:11 pm

Enemy spawnage

Post by Mr. Russian »

Me and my friends have been coding a game similar to the Atari game asteroids and I was having a bit of trouble spawning enemies (squares) on a time delay.
I have this much so far can any one help me along?

function love.load()
enemy = {x = 300, y = 300, angle = 0,speed = 50}
timer = 1
end

function newDirection()
-- This line allows arbitrary angles
-- enemy.angle = love.math.random()*2*math.pi

-- This line only allows up,down,left,right
enemy.angle = love.math.random(0,3)*0.5*math.pi

timer = 1
end

function moveenemy(dt)
enemy.x = enemy.x + math.cos(enemy.angle)*enemy.speed*dt
enemy.y = enemy.y + math.sin(enemy.angle)*enemy.speed*dt
end

function love.update(dt)
timer = timer - dt
if timer < 0 then
newDirection()
end
moveenemy(dt)
end
User avatar
Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

Re: Enemy spawnage

Post by Plu »

Your main problem seems to be that you only have 1 enemy. You have to maintain a table full of enemies and then insert new ones into it, if you want to have multiple at the same time.
Also use [ code] blocks around code, that helps with the formatting :)

Code: Select all


function love.load()
  enemies = { {x = 300, y = 300, angle = 0,speed = 50} } -- make a table to contain a list of enemies, and insert the first one
  timer = 1 
end

-- pass the enemy to move into the function so that it moves the correct one
function moveenemy( enemy, dt )
  enemy.x = enemy.x + math.cos(enemy.angle)*enemy.speed*dt
  enemy.y = enemy.y + math.sin(enemy.angle)*enemy.speed*dt 
end

function love.update(dt)
timer = timer - dt
if timer < 0 then
newEnemy()
timer = 1 -- reset the timer so it can continue to keep spawning. keep in mind that one per second is a lot!
end
for k, enemy in ipairs( enemies ) do
  moveenemy(enemy, dt)
end

function newEnemy()
  table.insert( enemies, {x = 300, y = 300, angle = 0,speed = 50} ) -- this makes them spawn on the same location, so you'll want to update this later
end
Note that if you have a draw function you'll have to update that one to call each enemy's draw function in turn as well.
end
Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests