This example demonstrates moving a model between predefined waypoints, visualized as colored cubes. After clicking in the canvas to focus the keyboard on it, the number keys 1, 2, and 3 may be used to trigger the movement.
The VWBug
constructor starts by defining the speed of the model and it's goal. It's goal is exactly where it currently is, so no movement will be necessary until the user issues a command.
function VWBug(scene,loc) {
this.speed = 1.0;
this.goal = loc;
When the user presses a key, a key press handler sets the goal of the bug to be the position of the appropriate cube. The render function renderFunc
then animates the model.
var dx = new THREE.Vector3();
dx.sub(bug.goal,bug.mesh.position);
if (dx.length() > closeEnough) {
dx.normalize();
dx.multiplyScalar(dt*bug.speed);
bug.mesh.position.addSelf(dx);
}
The vector dx
will contain the change in position that our model needs for the current frame. It is initialized to the vector from the model's current position to its goal. If that vector is short enough, we don't need to move the model any more. But if it's not, this vector is normalized to a unit (length one) vector, which is then scaled to be the appropriate length given the elapsed time and the model's speed. The mesh position is then updated.