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

如何让节点从最近方向补间旋转至目标角度?

实现Tween旋转时沿最近方向补间的解决方法

问题场景

当前使用Tween实现实体旋转,代码如下:

if (this._direction != AutomobileDirection.Up)
{
    if (this._rotationTweenIsActive())
    {
        this._stopRotationTween();
    }
    this._direction = AutomobileDirection.Up;
    this._initRotationTween();
    this._rotationTween.TweenProperty(this._collision, "rotation_degrees", 180, 0.3);
}

遇到的问题:当this._collision.Rotation为-45度时,Tween会沿最远路径旋转到180度,而非最近的方向。

解决方案

核心思路是计算目标角度的等效值,让当前角度到目标角度的差值落在[-180°, 180°]范围内,这样Tween就会自动选择最短路径旋转。

修改后的代码如下:

if (this._direction != AutomobileDirection.Up)
{
    if (this._rotationTweenIsActive())
    {
        this._stopRotationTween();
    }
    this._direction = AutomobileDirection.Up;
    this._initRotationTween();

    // 获取当前旋转角度
    float currentRotation = this._collision.Rotation;
    // 原始目标角度
    float targetRotation = 180f;

    // 计算最短路径的目标角度
    float angleDiff = targetRotation - currentRotation;
    // 将差值归一到0-360度范围
    angleDiff = (angleDiff + 360f) % 360f;
    // 如果差值超过180度,取反向路径
    if (angleDiff > 180f)
    {
        angleDiff -= 360f;
    }
    // 得到调整后的目标角度
    float adjustedTarget = currentRotation + angleDiff;

    // 使用调整后的目标角度执行补间
    this._rotationTween.TweenProperty(this._collision, "rotation_degrees", adjustedTarget, 0.3);
}

原理说明

角度是周期性循环的(360°为一个周期),直接使用原始目标角度时,Tween会按数值差的绝对值执行动画。通过将角度差调整到[-180°, 180°]区间,我们强制让补间选择最短的旋转路径:

  • 当当前角度为-45°,原始目标180°的差值为225°(超过180°),调整后差值变为-135°,对应逆时针旋转135°(最短路径),最终等效目标角度为-180°(和180°方向一致)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 07:37:15