I am currently working on implementing smooth camera movement using Three.js. The current setup allows me to click, hold, and drag to move around the scene with the camera following. However, I want to achieve a smoother movement similar to the acceleration and deceleration effect seen on this website: . At the moment, when I release the click after dragging, the camera abruptly stops. I aim to replicate the dampening effect of Three.js's OrbitalControls.
import * as THREE from "three";
export default class Experience {
constructor(options = {}) {
this.camera = new Camera();
this.renderer = new Renderer(this.canvas);
this.drag = new THREE.Vector2();
this.animate();
this.onMouseDrag();
}
updateCamera(event) {
if (event.movementX > 0) {
this.drag.x -= event.movementX * 0.01;
} else {
this.drag.x -= event.movementX * 0.01;
}
if (event.movementY > 0) {
this.drag.y -= event.movementY * 0.01;
} else {
this.drag.y -= event.movementY * 0.01;
}
this.camera.position.x = this.drag.x;
this.camera.position.z = this.drag.y;
}
onMouseDrag() {
let holder = this.updateCamera.bind(this);
window.addEventListener("mousedown", () => {
window.addEventListener("mousemove", holder);
});
window.addEventListener("mouseup", () => {
window.removeEventListener("mousemove", holder);
});
}
animate() {
requestAnimationFrame(this.animate.bind(this));
this.renderer.render(this.scene, this.camera);
}
}
My attempted solution so far involves adjusting the camera position based on mouse movements but results in jittery movements. Once the mouse is released, the camera smoothly transitions to its target position. To address the issue of jerky movement, I have made some adjustments:
constructor(options = {}) {
this.cameraTargetPosition = new THREE.Vector3(0, 20, 12); //added starting position
// ...
}
updateCamera(event) {
if (event.movementX > 0) {
this.cameraTargetPosition.x -= event.movementX * 0.01; //changed these from "this.drag"
} else {
this.cameraTargetPosition.x -= event.movementX * 0.01;
}
if (event.movementY > 0) {
this.cameraTargetPosition.y -= event.movementY * 0.01;
} else {
this.cameraTargetPosition.y -= event.movementY * 0.01;
}
}
animate() {
this.camera.position.lerp(this.cameraTargetPosition, 0.4); //added this
//...
}