定义平台的更短方式

所以基本上我有这段代码,用来控制我游戏中的平台(我希望创建一个2D平台游戏),在这个游戏中(Love2D Lua),这是脚本

platforms = {}
platform1 = { x = 0, y = 600, width = 279, height = 49 }
platform2 = { x = 279, y = 600, width = 279, height = 49 }
platform3 = { x = 558, y = 600, width = 279, height = 49 }
table.insert(platforms, platform1)
table.insert(platforms, platform2)
table.insert(platforms, platform3)

是否有更好的控制/创建平台的方式?

点赞
用户1190388
用户1190388

由于只有x值发生了改变:

platforms = {}
for _, x in ipairs{0, 279, 558} do
    table.insert(platforms, {x = x, y = 600, width = 279, height = 49})
end
2016-08-21 19:27:51
用户107090
用户107090

要将 platforms 用作数组(这似乎是您想要的):

platforms = {
  { x = 0, y = 600, width = 279, height = 49 },
  { x = 279, y = 600, width = 279, height = 49 },
  { x = 558, y = 600, width = 279, height = 49 },
}
2016-08-21 22:17:39
用户1836540
用户1836540

如果你的平台大小相同,你可以使用以下代码:

platforms = {
    { x = 0, y = 600 },
    { x = 279, y = 600 },
    { x = 558, y = 600 },
};
for _,v in ipairs(platforms) do
    v.width = 279;
    v.height = 49;
end
2016-08-21 22:19:54
用户6336645
用户6336645

正如其他人所说,在声明表格时可以将它们放在其中声明。

platforms = {
    { x = 999, y = 999, w = 999, h = 99 },
    ...
}

一旦你建立了这个表格,你就可以随时添加内容。

table.insert(platforms, { x = 111, y = 111, w = 111, h = 111 })

或者删除其中一个,只要你知道它的索引(在列表中的位置)。

table = {
    { }, -- 索引 1
    { }, -- 索引 2
    ...
}

然后删除其中一个:

table.remove(platforms, 1)

这将删除索引为 1 的平台。

要筛选它们,可以使用 ipairs。

for i, v in ipairs(platforms) do
    v.y = v.y - 10 * dt -- 做一些事情,这将逐渐提高所有平台
end

这应该是你需要的所有内容,玩得开心!

2016-08-22 07:03:48