Wasd and Qe

In which you trigger the camera's behaviors using the keyboard.

Many games let the player move the camera with the W, A, S, D keys. Some let the player yaw the camera with other keys, like Q and E. A key listener responds to each of these events with a single call to a camera method. It might look like this in pseudocode:

function onKeyDown
  if key is 'w'
    camera.advance(moveDelta)
  else if key is 's'
    camera.advance(-moveDelta)
  else if key is 'a'
    camera.strafe(-moveDelta)
  else if key is 'd'
    camera.strafe(moveDelta)
  else if key is 'q'
    camera.yaw(turnDelta)
  else if key is 'e'
    camera.yaw(-turnDelta)
  re-render

You may want to also support the cursor keys.

Try moving and turning the camera in the renderer below. Click on the canvas to give it keyboard focus before pressing the keys.

There are no Easter eggs. You'll find nothing but a grid in all directions. As you look around, you might notice that the movement is choppy. The severity of the choppiness depends on your operating system's key repeat rate. If the key repeat rate is fast, then new keydown events will be generated more quickly and the movement will be smoother.

Probably you do not want to force your users to change the system-wide repeat rate in order to get smooth rendering. Smoothness can be achieved in other ways. For example, you could switch to continuous rendering using requestAnimationFrame. On each frame, you update the camera based on which keys are currently down.

The browser doesn't let you query the state of a key, so you'll have to track their state manually through event listeners. This pseudocode tracks the direction of movement and turning in three global variables:

// These will be -1, 0, or 1.
horizontal = 0
vertical = 0
turn = 0

function onKeyDown
  if key is 'w'
    vertical = 1
  else if key is 's'
    vertical = -1
  else if key is 'a'
    horizontal = -1
  else if key is 'd'
    horizontal = 1
  else if key is 'q'
    turn = 1
  else if key is 'e'
    turn = -1

function onKeyUp
  if key is 'w' or 's'
    vertical = 0
  else if key is 'a' or 'd'
    horizontal = 0
  else if key is 'q' or 'e'
    turn = 0

The animate callback inspects these three variables and updates the camera accordingly. To ensure the physical changes aren't dependent on the frame rate, the amount of rotation or movement is tempered by how much time has passed since the last frame.

Try moving and turning the camera in this renderer that uses continuous rendering to smooth out the camera changes:

Continuous rendering is typical in animated graphics applications. However, be aware that it will consume much more energy than discrete, event-driven rendering.