Game Development Reference
In-Depth Information
Creating a ray segment
To create a ray segment, we need two components, origin and direction. The origin
is straightforward. The NDC ( x1 , y1 , 1) converted world coordinate will become
our origin, but the direction is tricky. We either use the direction of the camera or
alternatively, we can create two vectors with a varying z to calculate the direction.
In the following diagram, we have depicted two NDCs, originVector ( x1 , y1 , -1 ) and
startVector ( x1 , y1 , 1 ), lying on the light ray; one lying behind and the other ahead of
the camera (eye vector). We subtract one vertex from another to get the direction:
Object
Screen
Origin (x1,y1,-1)
Origin (x1,y1,1)
Eye
Ray
Open the RayCaster.js file from primitive/game in your favorite editor. The
following code snippet is present in this file:
RayCaster.prototype.makeRay=function(x,y){
var x1 = ( x / this.screen_width )*2 - 1;
var y1 = ( y / this.screen_height)*2 - 1;
var startVector=vec3.fromValues(x1,y1,1);
var originVector=vec3.fromValues(x1,y1,-1);
var directionVector=this.camera.unProjectVector(startVector);
var origin=this.camera.unProjectVector(originVector);
vec3.sub(directionVector,directionVector,origin);
vec3.normalize(directionVector,directionVector);
//vec3.scale(directionVector,directionVector,-1);
return {origin: origin, directionVector: directionVector};;
}
The function takes the canvas click coordinates ( x , y ) as parameters. It converts them
to NDC ( x1 , y1 ) after dividing them with the height and width of the canvas. We
create our two vectors: startVector ( x1 , y1 , 1 ) and originVector ( x1 , y1 , -1 ). Then,
we unproject both the vectors to convert them from NDC to world coordinates and
store them in the origin and directionVector variables.
 
Search WWH ::




Custom Search