Notifications
Clear all

[Closed] sort array based on pos.X

I’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

5 Replies

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

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

Thanks for the help.

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

Why you don’t use the world [0,0,0] as reference point?