PDA

View Full Version : sort array based on pos.X

 JokerMartini02-21-2012, 10:05 PMI'm trying to figure out a way to sort and array of objects based on their x position in world space. This seems like it should work but it is giving undesired results. collection = selection as array fn fnComparePositionX obj1 obj2 = ( obj1Pos = (in coordsys world obj1.pos).x obj2Pos = (in coordsys world obj2.pos).x if(obj1Pos < 0) then obj1Pos *= -1 if(obj2Pos < 0) then obj2Pos *= -1 local d = obj1Pos - obj2Pos case of ( (d < 0): -1 (d > 0): 1 default: 0 ) ) qsort collection fnComparePositionX clearlistener() print collection
Pjanssen
02-21-2012, 10:27 PM
It seems to me like this comparison function should be sufficient:
fn fnComparePositionX obj1 obj2 =
(in coordsys world obj1.pos).x - (in coordsys world obj2.pos).x

JokerMartini
02-21-2012, 10:39 PM
I was overthinking it

data = selection as array
fn sortByX obj1 obj2 = if obj1.pos.x < obj2.pos.x then -1 else if obj1.pos.x > obj2.pos.x then 1 else 0
qsort data sortByX
print final

JokerMartini
02-21-2012, 11:05 PM
Thanks for the help.

JokerMartini
02-21-2012, 11:17 PM
I'm not sure what was happening but I was getting odd results with yours as well.
Here is what I got working.

data = selection as array
fn sortByX obj1 obj2 dir: = if (in coordsys world obj1.pos)[dir] < (in coordsys world obj2.pos)[dir] then -1 else if (in coordsys world obj1.pos)[dir] > (in coordsys world obj2.pos)[dir] then 1 else 0
qsort data sortByX dir:1
clearlistener()
print data

miauu
02-22-2012, 05:12 PM
Why you don't use the world [0,0,0] as reference point?

CGTalk Moderation
02-22-2012, 05:12 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.