Best practice for destroying enemies in array
Posted: Thu Aug 18, 2016 5:22 am
Heya! First few days with Love2d here - I was wondering what the 'right' way to remove an object from a table is. I'd like to destroy it at the "destroy here..." point.
Also any ideas about best practices or what to read up on for larger love2d oriented games, I'd love to hear.
Thanks in advance!
Also any ideas about best practices or what to read up on for larger love2d oriented games, I'd love to hear.
Thanks in advance!
Code: Select all
-- Bubbles
io.stdout:setvbuf("no")
local bubbles_spritesheet
local tileSize = 16
local currentSprite = 1
local bubbles = {}
local bubbles = {}
local Bubble = {}
function Bubble.new(x, y)
local self = self or {} -- If I don't exist yet, make yourself
self.animations = {
floating = {
frames = {
getRect(0, 0)
}
},
bursting = {
frames = {
getRect(0, 1), getRect(0, 2), getRect(0, 3)
},
endAction = "destroy"
}
}
self.animation = {}
self.animation.name = "floating"
self.animation.frame = 1
self.dt30 = 0
self.x = x
self.y = y
self.age = 0;
self.update = function(dt)
self.dt30 = self.dt30 + dt * 30;
if self.dt30 > 1 then
self.dt30 = self.dt30 - 1 -- assumption that we shouldn't get more than a second out of whack
self.advanceFrame()
end
self.y = self.y - dt * 30 - (math.random() -.2) * 3
self.x = self.x + (math.random() -.2) * dt * 100
self.age = self.age + dt;
if(self.age > 3) then
self.animation.name = "bursting"
end
end
self.advanceFrame = function()
local anim = self.animations[self.animation.name]
local length = table.getn(anim.frames)
if self.animation.frame < length then
self.animation.frame = self.animation.frame + 1
else
if anim.endAction then
print("destroy here...")
end
self.animation.frame = 1
end
end
self.draw = function()
local anim = self.animations[self.animation.name]
local q = anim.frames[self.animation.frame]
love.graphics.draw(bubbles_spritesheet, q, self.x, self.y, 0, 2, 2)
end
return self
end
function love.load()
love.graphics.setDefaultFilter("nearest", "nearest", 1)
bubbles_spritesheet = love.graphics.newImage("bubbles_16.png")
aBubble = Bubble.new(200, 200)
for i = 0, 200 do
local b = Bubble.new(0 + math.random() * 700, 500 )
table.insert(bubbles, b)
end
end
function love.update(dt)
for k, b in pairs(bubbles) do
b.update(dt)
end
end
function love.draw()
for k, b in pairs(bubbles) do
b.draw()
end
end
function getRect(sx, sy)
local left = sx * tileSize
local top = sy * tileSize
local quad = false;
quad = love.graphics.newQuad(left, top, tileSize, tileSize, bubbles_spritesheet:getDimensions())
return quad
end