You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spark AR JS脚本问题:触摸触发3D对象每次平滑旋转90度失效

Spark AR 3D对象触摸平滑旋转问题修复

你的代码核心问题在于timeDriver只能被启动一次,且每次动画的采样器都是从0开始到360度,没有基于当前角度累加旋转。以下是修复后的代码,同时简化了计数逻辑:

const Scene = require('Scene');
const Reactive = require('Reactive');
const TouchGestures = require('TouchGestures');
const Diagnostics = require('Diagnostics');
const Animation = require('Animation');

(async function () {
    const myobject = await Scene.root.findFirst('BOX');
    // 记录当前旋转角度(初始为0,单位:弧度)
    let currentRotation = 0;
    // 单次旋转90度对应的弧度值
    const quarterTurnRad = Math.PI / 2;

    TouchGestures.onTap().subscribe(function () {
        // 计算目标角度:当前角度 + 90度
        let targetRotation = currentRotation + quarterTurnRad;
        
        // 第四次触摸后重置为0(360度=2π,等价于0)
        if (targetRotation >= 2 * Math.PI) {
            targetRotation = 0;
        }

        // 每次触摸创建新的时间驱动,确保动画可重复触发
        const timeDriver = Animation.timeDriver({
            durationMilliseconds: 500, // 可根据需求调整旋转速度
            loopCount: 1,
            mirror: false
        });

        // 创建从当前角度到目标角度的线性采样器
        const sampler = Animation.samplers.linear(currentRotation, targetRotation);
        // 绑定旋转动画到X轴
        myobject.transform.rotationX = Animation.animate(timeDriver, sampler);
        
        // 启动动画
        timeDriver.start();
        
        // 更新当前角度记录
        currentRotation = targetRotation;
        
        Diagnostics.log(`当前旋转角度:${currentRotation / Math.PI * 180}度`);
    });
})();

关键改动说明:

  • 每次触摸新建timeDriver:Spark AR的timeDriver启动后会进入完成状态,无法再次启动,因此每次触摸都需要创建新的驱动实例
  • 累加旋转角度:通过currentRotation变量记录当前角度,每次触摸在原有基础上增加90度,保证旋转动作连续
  • 重置逻辑:当目标角度达到360度(2π弧度)时,直接重置为0,实现循环效果
  • 优化动画时长:原代码5000ms的旋转速度过慢,调整为500ms更符合平滑旋转90度的预期,可按需修改

内容的提问来源于stack exchange,提问作者Patrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 17:40:36