lua - 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 无法识别“自我”。
解决方案
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
推荐阅读
- python - 如何使用 Python 点击并提交数据
- swift - 如何最好地在 SpriteKit 中编写 Undo 函数?
- jquery - 使用动态和静态输入php序列化并插入到mysql表单
- reactjs - 将 redux thunk 操作链接在一起
- android - 使用存储在 Firebase 数据库中的位置在谷歌地图上自定义绘图
- javascript - 如何在js sortBy和Join中对ACS进行排序?
- java - Storm:实时获取前十名用户
- android - 如何在 android 的 AccessibilityServiceInfo (AccessibilityService) 中最好地使用 packageNames
- asp.net-core - Asp.net Core 2.0 无法请求 *.properites 文件 .Reponse 404 Not Found
- xslt - 在 xsl 变量中对两个变化的单词进行子串化