0

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'.

Exorsky
  • 15
  • 3
  • what do you mean with doen't work? are you facing errors? or how does the expected behaviour differ from the actual one? – Piglet Apr 15 '21 at 09:06
  • Yes, i have compilation error. Local instance also doesn't work. Maybe there is different solution to make objects with self parametrs in corona/solora2d? – Exorsky Apr 15 '21 at 09:17
  • and don#t you think it would make sense to share that error message with us? – Piglet Apr 15 '21 at 09:17
  • main.lua:22 bad argument #1 to 'newRect' (number expected, got nil) stack traceback: [C]: in function 'newRect' main.lua:22 in function 'draw' main.lua:27: in function 'drawAll' main.lua:38: in main chunk – Exorsky Apr 15 '21 at 09:21
  • see my edited answer. – Piglet Apr 15 '21 at 09:24

1 Answers1

1
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

Piglet
  • 27,501
  • 3
  • 20
  • 43