Corona SDK / Solar2D 多个移动对象

我在制作具有随机移动速度的多个对象方面遇到了问题。 例如,我需要制作 1000 个对象并以随机速度和方向移动它们。

OOP 方法无法解决这个问题,但在 Love2d 中却可以毫无问题地解决。

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)

这段代码不起作用,似乎 Solar2D 不认识 'self'。

点赞
用户2858170
用户2858170
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 应该是局部变量!

同时,

function particle.drawAll()
  for i,instance in ipairs(ActiveParticle) do
    particle:draw()
  end
end

应该使用 instance:draw(),因为你想画实例不是 particle。否则,self 将不引用 instance,因此你无法访问其成员。

或者使用 particle.draw(instance)

由于 __index 元方法,instance:draw() 将解析为 particle.draw(instance),所以在 particle.draw 中,self 引用 instance

2021-04-15 09:10:10