Picking help

I've looked at the tutorial class for picking and I have a question.  The tutorial describes how to get the geometry under the cursor but how do you get to the object associated with the geometry?



As an example, lets say that I subclass Box to make MyBox.  I create a MyBox, put it in to the scene graph, and then pick it.  I get a reference to MyBox's geometry but not a reference to the MyBox class itself so that I can do things other than randomly recolor the box :slight_smile:



After searching on picking, I noticed that someone else said to use instanceOf with the picking results… specifically, they recommended this:



Spatial pickedObject = getPickResult();
if (pickedObject instanceof MyObject) {
    MyOjbect myObjecy = (MyObject) pickedObject;
    myObject.myMethod();
}



But you can't assign a PickResults object to a Spatial.  I'm confused.  The following does not work:


Ray mouseRay = new Ray(worldCoords, worldCoords2
               .subtractLocal(worldCoords).normalizeLocal());
         // Does the mouse's ray intersect the box's world bounds?
         pr.clear();
         rootNode.findPick(mouseRay, pr);

Spatial test = pr;



pr is a PickResult but you can't assign it to a Spatial and thus the rest of his suggested code is not working for me...

Any help would be greatly appreciated.

You need to get the selected object from pickresults with something like this:



   Ray mouseRay = new Ray(worldCoords, worldCoords2.subtractLocal(worldCoords).normalizeLocal());
   pr.clear();
   rootNode.findPick(mouseRay, pr);

   Spatial test = null;

   if(pr.getNumber() > 0)
      test = (Spatial)pr.getPickData(0).getTargetMesh();



And notice that there may be more than one result in the pick results. You can tell it to check distance and then you can iterate through the results if you want the closest one to the camera. Search the forum, the information is out there!  8)

That does not seem to work either… getTargetMesh() returns a GeomBatch which can't be cast in to a Spatial…



At least Eclipse doesn't believe it can :slight_smile:

I have found the answer to my question… for posterity, this is the correct code:



Spatial test = null;

   if(pr.getNumber() > 0) //Or loop, or distance check
      test = (Spatial)pr.getPickData(0).getTargetMesh().getParentGeom();

This was also exactly what I was looking for. I just wanted to thank you for posting your find here on the forum for others also to find :slight_smile: