我在制作具有随机移动速度的多个对象时遇到问题。例如,我需要制作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”。
发布于 2021-04-15 17:10:10
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)
endinstance应该是本地的!
也是
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
https://stackoverflow.com/questions/67105302
复制相似问题