【发布时间】:2021-07-10 07:17:28
【问题描述】:
我无法以随机移动速度制作多个对象。 例如,我需要制作 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 无法识别“自我”。
【问题讨论】:
-
不工作是什么意思?你面临错误吗?或者预期行为与实际行为有何不同?
-
是的,我有编译错误。本地实例也不起作用。也许有不同的解决方案可以在 corona/solora2d 中制作具有自身参数的对象?
-
您不认为与我们分享该错误消息有意义吗?
-
main.lua:22 错误参数 #1 到“newRect”(预期数字,得到 nil)堆栈回溯:[C]:在函数“newRect”中 main.lua:22 在函数“draw”中main.lua:27: 在函数“drawAll”中 main.lua:38: 在主块中
-
查看我编辑的答案。