moving ahead

Previously we rotated a model. Now we'll translate it as well as rotate under user control.

First we set up some speed constants.

var rotationSpeed = 1.5;
var translationSpeed = 2.5;

We also set up key up and down event handlers. A and D turn left and right, while W and S drive forwards and backwards. The handlers must be installed on the window as previously.

Since the user can hold down the control buttons for any length of time, we define special variables to capture the state of the buttons.

var rotateLeft = false;
var rotateRight = false;
var moveAhead = false;
var moveBackwards = false;

The render function contains code to actually perform the animation. For rotation, the code is similar to a previous example. Translation is not much different.

if (moveAhead)
	dPos = dt*translationSpeed; 

The above is one quarter of the animation code. Here if the variable moveAhead indicates that we should translate forwards, the appropriate amount of translation is computed and the translateZ function implements it. Note that the +Z direction is forward in Three, and that the translateZ method uses the model's Z axis.

Note also that all rotation in this example uses the model's parent (i.e. the world) Y axis. This works fine because here the model's Y axis is the same as the parents's Y axis.

example 8: moving ahead