<script src="/lib/three.js" type="text/javascript"></script>
body{
	padding: 0;
	margin: 0;
	overflow: hidden;
	cursor: move;
}
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.rotation.x = -0.8;
camera.position.y = 3;
camera.position.z = 5;

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { wireframe: true } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );

var dir = {lr: 0, ud: 0};
var speed = 0.1;

window.addEventListener("keydown", event => {
  if (event.keyCode === 65) { //A
    dir.lr = -1;
  } else if (event.keyCode === 68) { //D
    dir.lr = 1;
  } else if (event.keyCode === 87) { //W
    dir.ud = 1;
  } else if (event.keyCode === 83) { //S
    dir.ud = -1;
  }
});

window.addEventListener("keyup", event => {
  if (event.keyCode === 65) { //A
    dir.lr = 0;
  } else if (event.keyCode === 68) { //D
    dir.lr = 0;
  } else if (event.keyCode === 87) { //W
    dir.ud = 0;
  } else if (event.keyCode === 83) { //S
    dir.ud = 0;
  }
});

var control = function () {
  // Move ball forward (multiply by -1 * speed to move backwards)
  var cameraDirection = camera.getWorldDirection().multiplyScalar(speed * dir.ud);
  cube.position.x += cameraDirection.x;
  cube.position.z += cameraDirection.z;
  
  var cameraSideways = new THREE.Vector3(cameraDirection.z, 0, -cameraDirection.x).multiplyScalar(speed * dir.lr);
  cube.position.x += cameraSideways.x;
  cube.position.z += cameraSideways.z;
  
  //console.log(dir);
}

var render = function () {
  requestAnimationFrame( render );

  renderer.render(scene, camera);
  
  control();
};

render();
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/three.js/86/three.js