I am currently working on a 3-D graphical website using three.js
. The theme of the website is a universe filled with text. My goal is to make the camera move forward when the left mouse button is clicked and backward when the right mouse button is clicked.
In the past, the camera would zoom in or out based on the mouse scroll movement. However, I need to change this functionality to use the left and right mouse clicks instead.
If the user holds down the left mouse button, the camera should continuously move backward.
The previous code for zooming with the scroll looked like this:
document.addEventListener('wheel', onMouseWheel, false);
function onMouseWheel( event ) {
camera.position.z += event.deltaY * 0.1; // move camera along z-axis
}
So, in reference to that code, I modified it as follows:
var hold = false;
document.addEventListener('contextmenu', onContextMenu, false);
document.addEventListener('mousedown', onMouseDown, false);
document.addEventListener('mouseup', onMouseUp, false);
function onContextMenu(event) { // Prevent right click
event.preventDefault();
}
function onMouseDown(event) {
hold = true;
switch (event.which) {
case 1: // if left click
moveForward();
break;
case 3: // if right click
moveBackward();
break;
}
}
function onMouseUp(event) {
console.log('mouse up');
hold = false;
}
function moveForward() {
while (hold === true) {
camera.position.z -= 0.1;
}
}
function moveBackward() {
while (hold === true) {
camera.position.z += 0.1;
}
}
This code allows the camera to move forward or backward depending on the value of the hold
variable. However, when running this code, the browser becomes unresponsive. I am looking for a solution to smoothly move the camera forward/backward.
Is there a way to address this issue?