How to pause mesh rotation on mouse down?

Hello,

I have a project that is loading 3D molecules through the .pdb loader.

The 3D molecules are rotating through this line in the animate function:

				requestAnimationFrame( animate );
				controls.update();

				const time = Date.now() * 0.0004;

				root.rotation.x = time;
				root.rotation.y = time * 0.7;

I would like the rotation to pause when the user clicks the mouse down. I have attempted to do that through this solution:

			const isMouseDown = false;
            const isMouseUP = true;


			window.addEventListener('mousedown', onMouseDown);
			window.addEventListener('mouseup', onMouseUp)


			function onMouseDown(){
				console.log("Mouse DOWN");
				isMouseDown = true;
				isMouseUP = false;

			  }
			  
			  function onMouseUp(){
				isMouseDown = false;
				isMouseUP = true;
				  console.log("Mouse UP");
			  }

			function animate() {

				requestAnimationFrame( animate );
				controls.update();

				const time = Date.now() * 0.0004;

				if(!isMouseUP){
				root.rotation.x = time;
				root.rotation.y = time * 0.7;
				}
				
				if(!isMouseDown){
				root.rotation.x = time * 0;
				root.rotation.y = time * 0;
				}


				render();

			}


However, it doesn’t seem to be working. Any ideas anyone? Would really appreciate the help with this one.

Might be missing something, but isn’t isMouseUP equivalent to !isMouseDown :thinking: ? So rewriting the code:

if (isMouseDown) {
  root.rotation.y = time * 0.7; // You currently do ask it to rotate when the mouse is down
}

if (isMouseUP) {
  root.rotation.y = time * 0.0; // And you ask it to stop rotating when the mouse is up
}

// NOTE Which in turn is equivalent to:

if (isMouseDown) {
  root.rotation.y = time * 0.7;
} else {
  root.rotation.y = time * 0.0;
}

// NOTE Which in turn is equivalent to a fancy:

root.rotation.y = time * (isMouseDown ? 0.7 : 0.0);

Your code overall is fine - but it feels like you did overcomplicate it a bit by negating and splitting a single value in two. :sweat_smile:

Thanks for the reply!

I’ve re-written the code to this based on your recommendation:

            const isMouseDown = false;


		    window.addEventListener('mousedown', onMouseDown);
			window.addEventListener('mouseup', onMouseUp);


			function onMouseDown(){
				console.log("Mouse DOWN");
				isMouseDown = true;

			  }
			  
			 function onMouseUp(){
				isMouseDown = false;
				  console.log("Mouse UP");
			  }


			function animate() {

				requestAnimationFrame( animate );
				controls.update();

				const time = Date.now() * 0.0004;

				root.rotation.y = time * (isMouseDown ? 0.7 : 0.0);

				render();

			}

However, I’m either getting no rotation on page load. Or if I change const isMouseDown = false; to = true, I get the rotation, but no working mouse event. Any ideas?

If that is exactly the code you’re using - then you are trying to reassign a const.