Header Sep
Mobile Java 3D Tips, Tricks & Code
 
My Rating Score
Login to rate page

December 2005
Picking objects in 3D space using JSR 184

[Back]

 

This article describes how you can pick objects in 3D space using the JSR 184 API. Examples of how this technique can be used include collision detection or selecting an object.

Download example MIDlet with source code>>

To demonstrate how objects can be selected in 3D space, five cubes are randomly placed in the scene and can be selected by the cursor.

The meshes are located at different x, y and z positions and can be selected and moved around.

The method used for picking can be found in the Group object.

public boolean pick(int scope,
                    float x,
                    float y,
                    Camera camera,
                    RayIntersection ri)
 
The ray is cast from the x, y coordinate on the near clipping plane towards the corresponding pixel on the far clipping plane. The x, y coordinate should have a value from (0,0) to (1,1) where (0,0) is the top left of the screen and (1,1) bottom right.
 
The RayIntersection parameter will be filled with information about the intersected mesh.
 
To make ray intersection work, make sure that all nodes are checked as enabled for picking: setPickingEnable(true);
 
Here is an example how the method can be used:
 
private void pick(){
    RayIntersection ray = new RayIntersection();
    float p1, p2;
    // Normalize, the viewport should be within the range of (0,0) - (1,1)
    p1 = (float)POINTER_X / (float)WIDTH;
    p2 = (float)POINTER_Y / (float)HEIGHT;
    boolean hit = group.pick(-1, p1, p2, camera, ray);
    float x=0, y=0, z=0;             // the intersection point
    float [] fray = new float[6];    // The origin (ox oy oz) and direction (dx dy dz) of the pick ray.
    RayIntersection ri = new RayIntersection();
    // get the distance to the intersected part mesh.
    if (hit)
    {
     ray.getRay(fray);
     x = fray[0] + fray[3] * ray.getDistance();
     y = fray[1] + fray[4] * ray.getDistance();
     z = fray[2] + fray[5] * ray.getDistance();
    }
}
 
 
Note that the distance returned is not the distance to the center of the Mesh but the distance to the intersected part of the mesh.
 
 
 
My Rating Score
Login to rate page