Issue : Selecting 3D object from click (casting ray)

Started by
0 comments, last by Norman Barrows 10 years, 3 months ago

I must be able to select a 3D object in a simple seen from a click. To do that I use Processing and OBJLoader (to load the models) but my issue is in one of the algorithm. Every model has a simple BoundingBox always aligned with the world.

This is how I get the ray :


public Ray getRayFromClick(int mouse_x, int mouse_y){ //3d normalized device coordinates 
float x = (2.0f * mouse_x) / width - 1.0f; float y = 1.0f - (2.0f * mouse_y) / height; 
float z = 1.0f; PVector ray_nds = new PVector(x, y, z);
//4d Homogeneous Clip Coordinates
float[] ray_clip = new float[4];
ray_clip[0]=ray_nds.x;
ray_clip[1]=ray_nds.y;
ray_clip[2]=-1;ray_clip[3]=1.0;

//4d Eye (Camera) Coordinates
float[] ray_eye = new float[4];
PMatrix proj_inv = p3d.projection.get();
proj_inv.invert();
proj_inv.mult(ray_clip,ray_eye);
ray_eye[2]=-1.0;ray_eye[3]=0.0;

//4d World Coordinates
float[] ray_wor4d = new float[4];
PVector ray_wor = new PVector();
p3d.modelviewInv.get().mult(ray_eye,ray_wor4d);
ray_wor.set(ray_wor4d[0],ray_wor4d[1],ray_wor4d[2]);
ray_wor.normalize();

//setup ray
Ray ray = new Ray();
ray.p.set(width/2.0,height/2.0,0);
ray.dir.set(ray_wor);

return ray;
}

This is how I try to get if there is a collision with a plane and if the collision contact is in the plan :


public boolean intersectInPlane(Ray ray, PVector center , PVector nPlane, PVector halfSize){
PVector nPlaneSub = new PVector();
nPlane.sub(nPlane,ray.p,nPlaneSub);
float t = -((float)ray.p.dot(nPlaneSub))/((float)ray.dir.dot(nPlane));
if(t<=0)
return false;
println(t);
ray.dir.mult((float)t);
ray.p.add(ray.dir);
PVector centerMax = new PVector(center.x+halfSize.x,center.y+halfSize.y,center.z+halfSize.z);
PVector centerMin = new PVector(center.x-halfSize.x,center.y-halfSize.y,center.z-halfSize.z);
if(ray.p.x>=centerMin.x && ray.p.x<=centerMax.x
&& ray.p.y>=centerMin.y && ray.p.y<=centerMax.y
&& ray.p.z>=centerMin.z && ray.p.z<=centerMax.z)
return true;
return false;
}

The 't' has some really weird values and the contact is never in the plane. The models are in Z=-500 but the t is something in the line of 516753 which is a bit much.

rXp

Advertisement

try a search of gamedev.net for the term "raypick".

the raypick demo in the older directx sdk's is some of the most reliable code to base your raypick code off of.

but as always, the intersection test at the far end is up to you.

Norm Barrows

Rockland Software Productions

"Building PC games since 1989"

rocklandsoftware.net

PLAY CAVEMAN NOW!

http://rocklandsoftware.net/beta.php

This topic is closed to new replies.

Advertisement