Enemies chasing player
Posted: Sat Jan 20, 2018 5:01 pm
Now I am stuck on a part where enemies are supposed to chase the player but the when i run the thing, it gives me an error where it tries to do an arithmetic on field 'x' and says its a nil value, but the enemies should probably be spawned already by the time the last piece is loaded.
I've tried multiple times with multiple different ways of making the enemies chase the player, but none work simply because of the error. Any and all help would be appreciated because I only recently got into Lua
Code: Select all
require("player")
enemy = {}
enemySpeed = 10
math.randomseed(os.time())
score = 0
enemyNumber = 5
killTimeStart = 10 -- time limit/ level
killTime = killTimeStart
maxw, maxh = love.window.getDesktopDimensions(display)
timer = 0
spawnTime = 5 -- delay of spawn in seconds
round = 4 -- this is the amount of time that is multiplied by delta time (1s) to add to time allowed for the next round
function enemySpawn(x,y,w,h)
for i = 1, enemyNumber do
enemy[#enemy + 1] = {x = math.random(0 and player.x - 320, player.x + 300 and maxw - 64), y = math.random(0 and player.y - 320, player.y + 300 and maxh - 64), w = 64, h = 64}
end
if #enemy <= enemyNumber then
enemyNumber = enemyNumber + math.random(1,3)
end
end
function collcheck(dt)
for i,v in ipairs(enemy) do --collision check for bullet vs enemy
for a,b in ipairs(bullet) do
if b.x < v.x+64 and b.y < v.y+64 and
b.x > v.x-8 and b.y > v.y-8 then
table.remove(enemy, i)
table.remove(bullet, a)
score = score + 1
end
end
end
end
function enemy:update(dt)
killTime = killTime - dt
if killTime < 0 and #enemy > 0 then
killTime = killTimeStart
end
if killTime >=0 and #enemy == 0 then -- if there's remaining kill time and there are no enemies on the screen, increase the round time by 5s
killTime = killTime + round*dt -- done
end
if #enemy == 0 then -- if all enemies are dead, start the timer for the next round (5s)
timer = timer + dt
if timer > spawnTime then
enemySpawn()
timer = 0
end
end
collcheck()
end
function enemy:draw()
for i,v in ipairs(enemy) do
love.graphics.setColor(255,0,200)
love.graphics.rectangle("fill", v.x, v.y, v.w, v.h)
end
end
function enemymove(dt)
for _,enememe in ipairs(enemy) do
local enemyDirectionX = player.x - enemy.x
local enemyDirectionY = player.y - enemy.y
local distance = math.sqrt(enemyDirectionX * enemyDirectionX + enemyDirectionY * enemyDirectionY)
end
if distance ~= 0 then
enemy.x = enemy.x + enemyDirectionX / distance * enemySpeed * dt
enemy.y = enemy.y + enemyDirectionY / distance * enemySpeed * dt
end
end