Book Image

Game Development with Three.js

By : Isaac Sukin
Book Image

Game Development with Three.js

By: Isaac Sukin

Overview of this book

The advent of WebGL and its inclusion in many browsers enabled JavaScript programs running in a web browser to access the GPU without a plugin or extension. Three.js is a next generation high-level library that makes it possible to author complex 3D computer animations that display in the browser using nothing more than a simple text editor. The development of these new tools has opened up the world of real-time 3D computer animations to a far broader spectrum of developers. Starting with how to build 3D games on the web using the Three.js graphics library, you will learn how to build 3D worlds with meshes, lighting, user interaction, physics, and more. Along the way, you'll learn how to build great online games through fun examples. Use this book as a guide to embrace the next generation of game development! Moving on from the basics, you will learn how to use Three.js to build game worlds using its core components, including renderers, geometries, materials, lighting, cameras, and scenes. Following on from this, you will learn how to work with mouse and keyboard interactions, incorporate game physics, and import custom models and animations. You will also learn how to include effects like particles, sounds, and post-processing. You will start by building a 3D world, and then create a first person shooter game using it. You will then be shown how to imbue this FPS game with a “capture the flag” gameplay objective. With Game Development with Three.js, you will be able to build 3D games on the Web using the Three.js graphics library.
Table of Contents (12 chapters)

Keyboard movement and mouse looking

In order to move our camera around, we're going to encapsulate some state, so let's define a KeyboardControls class in a new JavaScript file:

function KeyboardControls(object, options) {
  this.object = object;
  options = options || {};
  this.domElement = options.domElement || document;
  this.moveSpeed = options.moveSpeed || 1;

  this.domElement.addEventListener('keydown', this.onKeyDown.bind(this), false);
  this.domElement.addEventListener('keyup', this.onKeyUp.bind(this), false);

KeyboardControls.prototype = {
  update: function() {
    if (this.moveForward)  this.object.translateZ(-this.moveSpeed);
    if (this.moveBackward) this.object.translateZ( this.moveSpeed);
    if (this.moveLeft)     this.object.translateX(-this.moveSpeed);
    if (this.moveRight)    this.object.translateX( this.moveSpeed);
  onKeyDown: function (event) {
    switch (event.keyCode) {
      case 38: /*up*/
      case 87: /*W*/ this.moveForward = true; break;