Skip to content

Instantly share code, notes, and snippets.

@videlais
Created January 15, 2017 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save videlais/87d5f4d1633258193aeb9357b18dfd51 to your computer and use it in GitHub Desktop.
Save videlais/87d5f4d1633258193aeb9357b18dfd51 to your computer and use it in GitHub Desktop.
function animate() {
// Call the requestAnimationFrame function on the animate function
requestAnimationFrame( animate );
// Check the FirstPersonControls object and update velocity accordingly
playerControls();
// Render everything using the created renderer, scene, and camera
renderer.render( scene, camera );
}
function playerControls () {
// Are the controls enabled? (Does the browser have pointer lock?)
if ( controls.controlsEnabled ) {
// Save the current time
var time = performance.now();
// Create a delta value based on current time
var delta = ( time - prevTime ) / 1000;
// Set the velocity.x and velocity.z using the calculated time delta
velocity.x -= velocity.x * 10.0 * delta;
velocity.z -= velocity.z * 10.0 * delta;
// As velocity.y is our "gravity," calculate delta
velocity.y -= 9.8 * 100.0 * delta; // 100.0 = mass
if ( controls.moveForward ) {
velocity.z -= 400.0 * delta;
}
if ( controls.moveBackward ) {
velocity.z += 400.0 * delta;
}
if ( controls.moveLeft ) {
velocity.x -= 400.0 * delta;
}
if ( controls.moveRight ) {
velocity.x += 400.0 * delta;
}
// Update the position using the changed delta
controls.getObject().translateX( velocity.x * delta );
controls.getObject().translateY( velocity.y * delta );
controls.getObject().translateZ( velocity.z * delta );
// Prevent the camera/player from falling out of the 'world'
if ( controls.getObject().position.y < 10 ) {
velocity.y = 0;
controls.getObject().position.y = 10;
}
// Save the time for future delta calculations
prevTime = time;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment