I'm having issues with trying to implement movement of my object in three.js
. It's suppose to respond to cursor movement and rotate a bit, however when I put cursor on the window the object disappears.
I created this app using three.js
that loads an .gltf
object this way.
var loaded_gltf
const loader = new GLTFLoader();
loader.load('/keyboard.gltf', function(gltf) {
loaded_gltf = gltf.scene
scene.add( loaded_gltf );
})
I've setup the scene etc. and everything worked fine. But after adding this code:
document.addEventListener('mousemove', onDocumentMouseMove)
let mouseX = 0
let mouseY = 0
let targetX = 0
let targetY = 0
const windowHalfX = window.innerWidth / 2
const windowHalfY = window.innerHeight / 2
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX)
mouseY = (event.clientXY - windowHalfY)
}
const clock = new THREE.Clock()
const loop = () => {
targetX = mouseX * .001
targetY = mouseY * .001
const elapsedTime = clock.getElapsedTime()
if(loaded_gltf) loaded_gltf.rotation.y -= .05 * (targetX - loaded_gltf.rotation.y)
if(loaded_gltf) loaded_gltf.rotation.x -= .05 * (targetY - loaded_gltf.rotation.x)
if(loaded_gltf) loaded_gltf.rotation.z -= .05 * (targetY - loaded_gltf.rotation.x)
// controls.update()
renderer.render(scene, camera);
window.requestAnimationFrame(loop)
}
loop()
I started having issues with the object disappearing. I commented out every line of code that had something to do with OrbitControls
because I thought it might be intervening but that doesn't seem to change anything.
There's a typo on your onDocumentMouseMove
function. The property event.clientXY
doesn't exist, so this creates an undefined
value that breaks your rotations. You probably want event.clientY
instead.
You're also making another mistake in your loop by using rotation.x
twice, it looks like you should be using rotation.z
the second time.