首页 > 解决方案 > 我怎样才能让我的 GLTF 对象跟随在电话上使用触摸的人?

问题描述

使用有关three.js 和其他问题的资源,我创建了一个GLTF 模型,当鼠标在画布上移动时它会跟随鼠标(请参阅下面的代码笔)。

但是,当在我的安卓手机上查看页面时,模型不会像在 OrbitControls 中使用那样旋转以跟随触摸。我试图了解如何使用事件监听器;touchstart、touchend 和 touchmove,因为我认为这可能是我需要让它响应触摸事件,但不幸的是我不太擅长 JavaScript,而且对 three.js 很陌生。

一个工作示例(尽管我不知道他们是否使用three.js)将在此页面上:https ://garden-eight.com/ 。模型跟随鼠标,在移动设备上查看时跟随手指。

请问有人可以借用他们的专业知识吗?:)

我非常乐意提供更多信息。我没有在 StackOverflow 上问过很多问题。

https://codepen.io/Beddalla/pen/qGLeyR

        var loader = new THREE.GLTFLoader(); /* Creates a GLTF Loader */


        loader.load( 'https://api.codetabs.com/v1/proxy?quest=https://www.adambeddall.com/monkey.glb', function ( gltf ) { /* Path to model */
            scene.add( gltf.scene ); /* Adds the model to the scene */
            model = gltf.scene
        });

        var plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -4);
        var raycaster = new THREE.Raycaster();
        var mouse = new THREE.Vector2();
        var pointOfIntersection = new THREE.Vector3();
        canvas.addEventListener("mousemove", onMouseMove, false);

        function onMouseMove(event){
          mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
            mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
          raycaster.setFromCamera(mouse, camera);
          raycaster.ray.intersectPlane(plane, pointOfIntersection);
          model.lookAt(pointOfIntersection);
        }

标签: htmlthree.js

解决方案


此问题的一种解决方案是向事件添加事件侦听器touchmove,然后使用来自event.touches[ 0 ].clientX和的事件数据event.touches[ 0 ].clientY来计算相应的mouse向量。

function onTouchMove(event){

    mouse.x = ( event.touches[ 0 ].clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.touches[ 0 ].clientY / window.innerHeight ) * 2 + 1;

    // rest of your code

}

更新 Codepen:https ://codepen.io/anon/pen/VOgwvO

three.js R105


推荐阅读