Problematic pick order

I’m having a little problem with picking stuff via a MouseRay.



Pickings results don’t seem to come up depending on the range from the camera (like clostest first, second closest as second, and so on - or reverse, like farest first etc) as i expected it.

Instead they seem to come up sorted by their X coordinate.



Pictures say more than thousand words, so here are two pictures to illustrate what i mean:







First one shows a mouseray pick in x direction.

Everything is fine. The first obstacle (black boxlike object) seen from the camera is selected.









Second one shows the same bunch of obstacles, but in the opposite direction.

And here’s the problem. Instead of picking the first obstacle that is seen from the camera, the last one is picked.



This shows that picking order obviously isn’t determined along the pick vector starting at the camera position, but by x coordinate instead.







If you want to see the code, here it is:

(Although i think it’s quite straight forward)



Vector2f screenPos = new Vector2f();
screenPos.set(game.am.getHotSpotPosition().x, game.am.getHotSpotPosition().y);
Vector3f worldCoords = DisplaySystem.getDisplaySystem().getWorldCoordinates(screenPos, 0);
Ray mouseRay = new Ray(game.cam.getLocation(), worldCoords.subtractLocal(game.cam.getLocation()));
pickResults.clear();
globalObstacleNode.findPick(mouseRay, pickResults);

if(gamePickResults.getNumber() > 0){
//always pick the first object found
TriMesh targetMesh = (TriMesh) pickResults.getPickData(0).getTargetMesh().getParentGeom();
ObstacleUtils.markObstacle(targetMesh.getData(),game);
}



Shouldn't the ray of a mouse pick start at the camera position and then travel into the scene?
Or am I just doing something wrong?
How can i get the right result (= closest object always first)?
Apart from sorting all results additionally afterwards, of course, which i'd like to avoid.

Thank you

pickResults.setCheckDistance(true) might do what you want