我使用索引号
访问对象属性object = {}
object.y = {60,20,40}
object.g = {box1,box2,box3} -- graphic
object.c = {false,false,false} -- collision
-- object.y[2] is 20 and its graphic is box2
-- sorted by y location, index should be, object.sort = {2,3,1}
我知道table.sort
对列表进行排序,但是我如何对返回索引的y列表进行排序,以便根据y位置在前面绘制每个对象。
也许快速排序功能可以编辑,我不明白。 http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Lua
https://github.com/mirven/lua_snippets/blob/master/lua/quicksort.lua
这可能吗?
答案 0 :(得分:4)
不要像您当前那样存储数据。使用类似的东西:
object = {
{
y = 60,
g = box1,
c = false,
},
{
y = 20,
g = box2,
c = false,
},
{
y = 40,
g = box3,
c = false,
},
}
然后在table.sort
中使用以下回调函数:
function CustomSort(L, R)
return L.y > R.y
end
如下图所示:
table.sort(object, CustomSort)
答案 1 :(得分:3)
这应该有效:
public void onItemSelected(AdapterView<?> parent, View view, int itemPosition, long itemId) {
dialog = ProgressDialog.show(this, "", "Please wait", true);
// Google Places Access key and location values.
new readFromGooglePlaceAPI()
.execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
+ "location=53.795984,-1.759398&radius=900&sensor=true&"
+ "key=API_Key&types="
+ places[itemPosition]);
myList.OnItemSelectedListener (this);
return true;
}
使用此代码与您的代码组合时,temp将为{2,3,1}。
答案 2 :(得分:1)
@EinsteinK @ hjpotter92:谢谢
结果:这是我收到的答案的最终版本。我的问题已经解决了。
使用sortIndex(object)
在object.sort
中获取排序列表。在对象移动后更新排序。
box1 = love.graphics.newImage("tile1.png")
box2 = love.graphics.newImage("tile2.png")
box3 = love.graphics.newImage("tile3.png")
hero = love.graphics.newImage("hero.png")
object = {
{ x = 200, y = 50, g = box1 },
{ x = 50, y = 100, g = box2 },
{ x = 150, y = 200, g = box3 },
{ x = 0, y = 0, g = hero }
}
function sortIndex(item)
-- Sort id, using item values
local function sortY(a,b)
return item[a].y < item[b].y
end
--------------------------------
local i
local id = {} -- id list
for i = 1, #item do -- Fill id list
id[i] = i
end
-- print( unpack(id) ) -- Check before
table.sort(id,sortY)-- Sort list
-- print( unpack(id) ) -- Check after
item.sort = id -- List added to object.sort
end
sortIndex(object) -- print( unpack(object.sort) ) -- Check sorted id's
function drawObject()
local i,v, g,x,y
for i = 1, #object do
v = object.sort[i] -- Draw in order
x = object[v].x
y = object[v].y
g = object[v].g
love.graphics.draw(g,x,y)
end
end