I am currently working on achieving a smooth rotation of a gltf model while scrolling.
I have successfully developed a function that converts pageYOffset from pixels to radians
let scrollPositionRad = 0;
window.addEventListener("scroll", onWindowScroll );
function onWindowScroll(){
let scrollPosition = Math.round(pageYOffset);
let limit = document.body.offsetHeight - window.innerHeight;
scrollPositionRad = (scrollPosition * 2* Math.PI) / limit;
}
as well as a function that handles the rotation and centering of the model
function centerObj(rad){
obj.rotation.y = rad;
let box = new THREE.Box3().setFromObject( obj );
let center = box.getCenter( new THREE.Vector3() );
obj.position.x += ( obj.position.x - center.x );
obj.position.y += ( obj.position.y - center.y );
obj.position.z += ( obj.position.z - center.z );
}
However, when I attempt to animate by calling centerObj(scrollPositionRad), the gltf model disappears
renderer.setAnimationLoop(_ => {
centerObj(scrollPositionRad);
renderer.render(scene, camera);
})
Here is the model loading code after creating the scene
let loader = new THREE.GLTFLoader();
let obj = null;
loader.load('https://raw.githubusercontent.com/aaadraniki/projects/web-pages/assets/models/fender_br/scene.gltf', function(gltf) {
obj = gltf.scene;
scene.add(obj);
function centerObj(rad){
obj.rotation.y = rad;
let box = new THREE.Box3().setFromObject( obj );
let center = box.getCenter( new THREE.Vector3() );
obj.position.x += ( obj.position.x - center.x );
obj.position.y += ( obj.position.y - center.y );
obj.position.z += ( obj.position.z - center.z );
}
centerObj(0.8);
let scrollPositionRad = 0;
window.addEventListener("scroll", onWindowScroll );
function onWindowScroll(){
let scrollPosition = Math.round(pageYOffset);
let limit = document.body.offsetHeight - window.innerHeight;
scrollPositionRad = (scrollPosition * 2* Math.PI) / limit;
}
renderer.setAnimationLoop(_ => {
centerObj(scrollPositionRad);
renderer.render(scene, camera);
})
});