2016-08-21 47 views
2

表較短的方式所以基本上我有這樣的代碼,控制我的平臺(我想創建一個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) 

是有沒有更好的方法來控制/創建平臺?

回答

0

由於只有x價值得到改變:

platforms = {} 
for _, x in ipairs{0, 279, 558} do 
    table.insert(platforms, {x = x, y = 600, width = 279, height = 49}) 
end 
+0

如果Y也會改變怎麼辦?我應該輸入什麼內容'_',或者我應該輸入這個符號? – LostPuppy

+0

@LostPuppy,'_'符號表示您只是忽略該變量。你不需要'{0,279,558}'表的'1,2,3'鍵 – slavanap

1

要使用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 }, 
} 
2

如果你的平臺有其共同的大小你可以使用這樣的東西:

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 
0

正如其他人所說,要宣佈他們聲明時可以將它們放在表格中。

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

一旦你建立了表,你可以隨時添加它。

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

或者拿走一個,提供你知道它是哪個指數(它是多麼遠了名單)

table = { 
    { }, -- Index 1 
    { }, -- Index 2 
    ... 
} 

然後拿走一個:

table.remove(platforms, 1) 

這將刪除索引1下的平臺。

要篩選它們,您可以使用ipairs。

for i, v in ipairs(platforms) do 
    v.y = v.y - 10 * dt -- Do something, this would slowly raise all platforms 
end 

這應該是你所需要的,玩得開心!