I'm implementing a smooth scroll in Three.js based on this tutorial, it amounts to the following scroll listener:
window.addEventListener("wheel", onMouseWheel);
let y = 0;
let pos = 0;
function onMouseWheel(e) {
y = e.deltaY * 0.003;
particlesMesh.rotation.y += 0.0005;
}
And the following rendering:
const clock = new THREE.Clock();
const tick = () => {
// Scroll
pos += y;
y *= 0.9;
camera.position.y = -pos;
// Render
renderer.render(scene, camera);
window.requestAnimationFrame(tick);
};
tick()
My question is: How can I prevent the user being able to scroll up/down infinitely. I'm a little unsure on how the webgl canvas effects the dimensions of the page, but it seems to go on forever.
I have tried to add a condition to only allow scrolling down if y > 0, but the scrollbar simply gets stuck at the top.
Is there a simple solution to prevent scrolling up when y <= 0?
e.deltaY is not the scroll position; it is merely the direction of the scroll. e.deltaY is positive when scrolling down and negative when scrolling up.
It sounds like you want to add constraints around the camera.position.y variable. If so, then add a condition before pos += y:
if(camera.position.y < 0) {
...
}