首页 > 解决方案 > 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 无法识别“自我”。

标签: luacoronasdksolar2d

解决方案


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 selfinstance


推荐阅读