Game Development Reference
In-Depth Information
Cheating in the bullet action
In this section, we will talk about cheating in the physics world. For simplicity, the
code of the bullet should be similar to the grenade because all we need to do is to
change the direction vector of the impulse/force. The following code demonstrates
the application of impulse on our bullet object:
var impulse=jigLib.GLMatrix.multiplyVec3(this.initialModelMatrix,
[0,0,-2000]);
this.rigidBody.applyWorldImpulse(jigLib.Vector3DUtil.create
(impulse[0],impulse[1],impulse[2]),jigLib.Vector3DUtil.
create(pos.x,pos.y,pos.z));
We needed a strong impulse in the -Z direction, and that is it. However, most of the
time in games, we do want physics collisions detection but do not want the physics
engine to control the trajectory. So, let's visit a similar case. Open the
Bullet.js
ile
from
primitive/game
in your text editor.
The
initialize
function of the
Bullet
class is absolutely the same, except we check
if the rigid body is initialized. We initialize its position and add the body to the
physics system as follows:
Bullet.prototype.initialize=function() {
...
this.positions=[];
for(vari=0;i<count;++i){
this.positions.push(this.calculatePosition(i*this.steps));
}
if(this.rigidBody){
this.initializePosition();
this.system.addBody(this.rigidBody);
}
}
The
initializePosition
function takes an element from the
positions
array at
the
this.counter
value, transforms that value using
initialModelMatrix
from
the camera, and moves
rigidBody
to the new calculated position. This is where the
cheating happened. This function is also invoked from the
update
function. It simply
moves the
rigidBody
parameter to a predefined value; we did not let physics control
its motion/trajectory. Initially the counter is
0
to set the initial bullet location.
Bullet.prototype.initializePosition=function(){
var mat=mat4.create();
mat4.translate(mat,this.initialModelMatrix,this.
positions[this.counter]);
var newPos=jigLib.GLMatrix.multiplyVec3(mat,[0,0,-1]);
this.rigidBody.moveTo(jigLib.Vector3DUtil.create(newPos[0],
newPos[1],newPos[2]));
}