Game Development Reference
In-Depth Information
We will use the JigLib library to understand the implementation of a ray cast. JigLib
provides us with two classes to implement ray casting:
JRay
and
JSegment
. The
constructor of the
JRay
class is defined as follows:
JRay=function(_origin, _dir)
The constructor of this class takes two parameters,
_origin
and
_dir
. We will set
the
_origin
parameter to the position of the character and the
_dir
parameter to
the direction of the character. The position and direction can be easily derived from
our
matrixWorld
matrix. The position will be derived from the
m30
,
m31
, and
m32
components of our matrix and the direction vector can be calculated by multiplying
the forward vector with the rotation matrix (derived from
this.quaternion
of
our
StageObject
class) or retrieving the
m03
,
m13
, and
m23
components of our
matrixWorld
matrix. The
JRay
class is used internally by the
JSegment
class. We
will only interact with the
JSegment
class. The constructor of the
JSegment
class
is defined as follows:
JSegment=function(_origin, _delta)
The
JSegment
class is similar to the
JRay
class except that it takes the
_delta
parameter instead of the
_dir
parameter. The
_delta
parameter is the length of the
ray multiplied by the direction of the player. The
JSegment
class does not cast an
infinite ray, and the intersecting objects in the vicinity of the ray are returned. Let's
quickly take a peep into the implementation:
vec3.scale(directionVector,ray.directionVector,100)
var segment=new jigLib.JSegment(origin,directionVector);
var out={};
var cs=system.getCollisionSystem();
if(cs.segmentIntersect(out, segment, null)){
returnout.rigidBody;
}
First, we scale our direction vector by
100
, which is the length of our ray in the
example. Then, we create an object of the segment. We retrieve the object of our
collision system from the physics system object. We then check for an intersecting
object using the
cs.segmentIntersect(out, segment, null)
function. The last
parameter (
null
) is for the outer body, the enclosing body, not necessarily the parent
of the object. It can be a skybox or any similar object, which we will ignore for our
calculations. In our case, we do not pass the enclosing body; hence, we pass null.
If the function returns true, then the intersecting object is retrieved from the
out
variable, which we passed as the first parameter in the function call.