Created
February 23, 2021 15:55
-
-
Save lucasdidthis/dad475a712254c977a9a491d974a7e7e to your computer and use it in GitHub Desktop.
function to damp movement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const parameters = { | |
radius: 1.0, | |
moveSpeed: 0.01, | |
damping: 0.1, | |
tilt: 10, | |
} | |
const raycaster = new THREE.Raycaster() | |
const mouse = new THREE.Vector2() | |
const origin = new THREE.Vector3() | |
let velocity = new THREE.Vector3() | |
// inside the tick: | |
raycaster.setFromCamera(mouse, camera) | |
// Ray direction vector | |
const ray = raycaster.ray.direction | |
// Calculate the displacement vector between the cube and the final location | |
const xDelta = camera.position.clone() | |
.add( ray.normalize() ) | |
.sub( origin ) | |
.normalize() | |
.multiplyScalar( parameters.radius ) | |
.sub( cube.position ) | |
// Note: cube is always trapped inside an invisible sphere | |
// Acceleration from the drag force | |
const aDrag = xDelta.clone() | |
.multiplyScalar( parameters.moveSpeed ) | |
// Acceleration from the damping force | |
const aDamp = velocity.clone() | |
.multiplyScalar( parameters.damping ) | |
// Change the velocity | |
velocity = velocity.add( aDrag ) | |
.sub( aDamp ) | |
// Move the cube | |
cube.position.add( velocity ) | |
// Tilt the cube | |
const {x, y, z} = velocity.clone().multiplyScalar( parameters.tilt ) | |
cube.rotation.set(-z, x, y) | |
// Desktop | |
window.addEventListener('mousemove', (event) => { | |
mouse.x = event.clientX / sizes.width * 2 - 1 | |
mouse.y = - (event.clientY / sizes.height) * 2 + 1 | |
}) | |
// Mobile | |
window.addEventListener('touchstart', (event) => { | |
mouse.x = event.touches[0].clientX / sizes.width * 2 - 1 | |
mouse.y = - (event.touches[0].clientY / sizes.height) * 2 + 1 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment