Game Development Reference
In-Depth Information
Bullets
Finally, let's add shooting so we can pulverize those enemies! First, we'll create a
new
Bullet
class in
bullet.js
similar to what we did for the
Player
class. Bullets
are just meshes with a
direction
vector and a
speed
scalar, so their
update
method
can be pretty simple:
Bullet.prototype.update = (function() {
var scaledDirection = new THREE.Vector3();
return function(delta) {
scaledDirection.copy(this.direction).multiplyScalar(this.
speed*delta);
this.position.add(scaledDirection);
};
})();
We'll set bullets' directions when they're shot. Bullets can either be shot in the
camera's direction or from an enemy bot toward another player. To get the
relevant direction, our
shoot
function will look similar to the following code:
var shoot = (function() {
var negativeZ = new THREE.Vector3(0, 0, -1);
return function(from, to) {
bullet = new Bullet();
bullet.position.copy(from.position);
if (to) {
bullet.direction = to.position.clone().sub(from.position).
normalize();
}
else {
bullet.direction = negativeZ.clone().applyEuler(from.rotation);
}
bullets.push(bullet);
scene.add(bullet);
};
})();
We get the direction from one player to another by subtracting their positions.
If the user is shooting then we aren't necessarily aiming at anything, so we just
want the direction in which the camera is looking. We retrieve this direction
from the player's rotation.