首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >corona sdk / solar2d多移动对象

corona sdk / solar2d多移动对象
EN

Stack Overflow用户
提问于 2021-04-15 16:55:00
回答 1查看 108关注 0票数 0

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

OOP方法不起作用,但在love2d中,它没有任何问题。

代码语言:javascript
复制
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”。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-15 17:10:10

代码语言:javascript
复制
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应该是本地的!

也是

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67105302

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档