Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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