Game Development Reference
In-Depth Information
We calculate the direction vector after subtracting the origin from directionVector
and storing the result in the direction vector ( vec3.sub (directionVector,
directionVector, origin); ). As the direction vector is a unit vector, we
normalize it ( vec3.normalize (directionVector, directionVector); ). We then
return the origin and directionvector variables ( return {origin: origin,
directionVector: directionVector}; ) to the calling function.
Checking for an intersection
Once we have created our ray, all we have to do is invoke the segmentIntersect
function of our collision system to get the intersecting object.
Open the RayCaster.js file from primitive/game in your favorite editor. The
following code snippet is present in this file:
RayCaster=function(SCREEN_WIDTH,SCREEN_HEIGHT,camera){
this.camera=camera;
this.screen_height=SCREEN_HEIGHT;
this.screen_width=SCREEN_WIDTH;
this.pickedObject=null;
};
RayCaster.prototype.pickObject=function(x,y,system){
var ray=this.makeRay(x,y);
var directionVector=vec3.create();
//The constant 100 is added to define the range of the ray. In
our implementation, the ray is not infinite.
vec3.scale(directionVector,ray.directionVector,100)
var segment=new jigLib.JSegment(ray.origin,directionVector);
var out={};
var cs=system.getCollisionSystem();
if(cs.segmentIntersectGame(out, segment, null)){
if(this.pickedObject){
this.pickedObject.isPicked=false;
}
returnout.rigidBody;
}
}
The constructor of the RayCaster class takes the width and height of the canvas and
the camera object as parameters and stores them in the class variables.
 
Search WWH ::




Custom Search