# Opengl-es picking object

I saw a lot of picking code opengl-es, but nothing worked. Can someone give me what am I missing?

My code is (from tutorials/forums)

Vec3 far  = Camera.getPosition();
Vec3 near = Shared.opengl().getPickingRay(ev.getX(), ev.getY(), 0);

Vec3 direction = far.sub(near);
direction.normalize();

Log.e("direction", direction.x+" "+direction.y+" "+direction.z);

Ray mouseRay = new Ray(near, direction);

for (int n=0; n<ObjectFactory.objects.size(); n++) {
if (ObjectFactory.objects.get(n)!=null) {
IObject obj = ObjectFactory.objects.get(n);

float discriminant, b;

b = -mouseRay.getOrigin().dot(mouseRay.getDirection());

discriminant = FloatMath.sqrt(discriminant);

double x1 = b - discriminant;
double x2 = b + discriminant;

Log.e("asd", obj.getName() + " "+discriminant+"   "+x1+" "+x2);
}
}


my camera vectors:

//cam
Vec3 position   =new Vec3(-obj.getPosX()+x, obj.getPosZ()-0.3f, obj.getPosY()+z);
Vec3 direction  =new Vec3(-obj.getPosX(),   obj.getPosZ(), obj.getPosY());
Vec3 up         =new Vec3(0.0f, -1.0f, 0.0f);
Camera.set(position, direction, up);


and my picking code:

public Vec3 getPickingRay(float mouseX, float mouseY, float mouseZ) {

int[] viewport      = getViewport();
float[] modelview   = getModelView();
float[] projection  = getProjection();

float winX, winY;
float[] position    = new float[4];

winX = (float)mouseX;
winY = (float)Shared.screen.width - (float)mouseY;

GLU.gluUnProject(winX, winY, mouseZ, modelview, 0, projection, 0, viewport, 0, position, 0);

return new Vec3(position[0], position[1], position[2]);
}


My camera moving all the time in 3d space. and my actors/modells moving too. my camera is following one actor/modell and the user can move the camera on a circle on this model.

How can I change the above code to working?

• You'll have to try and explain exactly what is going wrong. – MichaelHouse Jan 4 '12 at 19:41
• As Sean said in a comment below, I would say abandon this approach and use ray-polygon intersections instead. – bobobobo Mar 8 '13 at 13:13
• Here's an excellent tutorial that helped me extract the picking ray: antongerdelan.net/opengl/raycasting.html The above approach is even better than the commonly used one. – Tara Sep 13 '13 at 7:55

There is a much easier way of picking which requires much less processing power. You simply give each model a specific color, render it without updating the screen, check if the mouse cursor is hovering over the color in question by calling glReadPixels (use PBOs if you want more performance), and then clear the screen and render normally. The non-pickable objects should be black.