会员登录|免费注册|忘记密码|管理入口 返回主站||保存桌面
手机陀螺仪实现同步3D模型旋转手机陀螺仪「手机陀螺仪实现同步3D模型旋转」
2025-02-19IP属地 湖北2

如题,代码如下

  // 创建场景、相机和渲染器

        const scene = new THREE.Scene();

        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

        const renderer = new THREE.WebGLRenderer();

        renderer.setSize(window.innerWidth, window.innerHeight);

        document.body.appendChild(renderer.domElement);

        // 创建正方体的几何体和材质

        const geometry = new THREE.BoxGeometry(1, 1, 1);

        const material = new THREE.MeshBasicMaterial({ color: 0x888888 });

        // 创建正方体对象

        const cube = new THREE.Mesh(geometry, material);

        scene.add(cube);

        // 设置相机位置

        camera.position.z = 5;

        let initialOrientation = null;

        // 判断设备是否支持陀螺仪

        if (window.DeviceOrientationEvent) {

            window.addEventListener('deviceorientation', handleOrientation, true);

        }

        // 陀螺仪事件处理函数

        function handleOrientation(event) {

            // 如果还没有初始陀螺仪方向,则将当前方向作为初始方向

            if (initialOrientation === null) {

                initialOrientation = {

                    beta: event.beta,

                    gamma: event.gamma

                };

            }

            // 从陀螺仪事件中获取方向信息

            const beta = event.beta - initialOrientation.beta; // 设备在x轴上旋转的角度相对于初始方向的差值

            const gamma = event.gamma - initialOrientation.gamma; // 设备在y轴上旋转的角度相对于初始方向的差值

            // 更新正方体的旋转

            cube.rotation.x = (beta / 180) * Math.PI; // 设置旋转角度与 beta 角度相对于初始方向的差值成比例

            cube.rotation.y = (gamma / 180) * Math.PI; // 设置旋转角度与 gamma 角度相对于初始方向的差值成比例

        }

        // 动画函数,每帧更新渲染

        function animate() {

            requestAnimationFrame(animate);

            renderer.render(scene, camera);

        }

        // 开始动画循环