I have problems with making multiple objects with random movement speed. For example, I need to make 1000 objects and move them with random speed in random direction.
OOP aproach doesn't work, but in love2d it works without any problems.
local displayWidth = display.contentWidth
local displayHeight = display.contentHeight
particle = {}
particle.__index = particle
ActiveParticle = {}
function particle.new()
instance = setmetatable({}, particle)
instance.x = math.random(20, displayWidth)
instance.y = math.random(20, displayHeight)
instance.xVel = math.random(-150, 150)
instance.yVel = math.random(-150, 150)
instance.width = 8
instance.height = 8
table.insert(ActiveParticle, instance)
end
function particle:draw()
display.newRect(self.x, self.y, self.width, self.height)
end
function particle.drawAll()
for i,instance in ipairs(ActiveParticle) do
particle:draw()
end
end
function particle:move()
self.x = self.x + self.xVel
self.y = self.y + self.yVel
end
for i = 1, 10 do
particle.new()
particle.drawAll()
end
function onUpdate (event)
instance:move()
end
Runtime:addEventListener("enterFrame", onUpdate)
This code doesn't works, seems solar2d doesn't recognize 'self'.
function particle.new()
instance = setmetatable({}, particle)
instance.x = math.random(20, displayWidth)
instance.y = math.random(20, displayHeight)
instance.xVel = math.random(-150, 150)
instance.yVel = math.random(-150, 150)
instance.width = 8
instance.height = 8
table.insert(ActiveParticle, instance)
end
instance
should be local!
Also
function particle.drawAll()
for i,instance in ipairs(ActiveParticle) do
particle:draw()
end
end
Should use instance:draw()
as you want to draw the instance not particle
. Otherwise self
will not refer to instance
so you cannot access it's members.
Alternatively use particle.draw(instance)
Due to the __index
metamethod instance:draw()
will resolve to particle.draw(instance)
so inside particle.draw
self
refers to instance