bs-community / skinview3d

Three.js powered Minecraft skin viewer.
https://skinview3d-demo.vercel.app
MIT License
550 stars 90 forks source link

Rotating head (look at mouse) like in Minecraft #140

Closed Mativve closed 1 year ago

Mativve commented 1 year ago

Hello

I'm having trouble turning my head. I want to get the same effect as in Minecraft but currently I have some bug in my code that calculates the rotation wrong. Can anyone help me or tell me what should I use?

Now: https://i.imgur.com/1sIQwdb.png

Expectations: https://i.imgur.com/07q7gnX.png

        const mouseX = event.clientX / window.innerWidth * 2 - 1;
        const mouseY = -event.clientY / window.innerHeight * 2 + 1;

        console.log(mouseX, mouseY);

        const headPosition = skinHeadPart.position.clone();
        const headWorldPosition = headPosition.applyMatrix4(skinHeadPart.matrixWorld);

        const mouseVector = new THREE.Vector3(mouseX, mouseY, 0.5);
        mouseVector.unproject(skinViewer.camera);

        const dir = mouseVector.sub(skinViewer.camera.position).normalize();
        const distance = (headWorldPosition.z - skinViewer.camera.position.z) / dir.z;
        const mousePosition = skinViewer.camera.position.clone().add(dir.multiplyScalar(distance));

        const rotationX = Math.atan2(-mousePosition.y - headWorldPosition.y, distance);
        const rotationY = Math.atan2(mousePosition.x - headWorldPosition.x, distance);

        skinHeadPart.rotation.x = rotationX;
        skinHeadPart.rotation.y = rotationY;

Thanks for any advice

Hacksore commented 1 year ago

@Mativve does this get you closer to a working impl?

https://codesandbox.io/p/sandbox/skinview3d-rotation-around-head-base-u5u7n

Mativve commented 1 year ago

@Hacksore Oh my god! Yes, thank you so so so much! That's so easy solution 🙏