首页 > 解决方案 > HLSL:Unitys Vector3.RotateTowards(...)

问题描述

我需要在计算着色器中以最大角度向另一个方向旋转方向向量,就像 Vector3.RotateTowards(from, to, maxAngle, 0) 函数一样。这需要在计算着色器内部进行,因为出于性能原因,我无法将所需的值从 GPU 发送到 GPU。关于如何实现这一点的任何建议?

标签: unity3dvectorrotationhlslangle

解决方案


这改编自vc1001在 Unity 论坛上的这篇文章demofox的这个 shadertoy 条目的组合。我还没有对此进行测试,并且自从我完成 HLSL/cg 编码以来已经有一段时间了,如果有错误,请让我知道是否存在错误——尤其是语法错误。

float3 slerp(float3 current, float3 target, float maxAngle)
{
    // Dot product - the cosine of the angle between 2 vectors.
    float dot = dot(current, target);     

    // Clamp it to be in the range of Acos()
    // This may be unnecessary, but floating point
    // precision can be a fickle mistress.
    dot = clamp(dot, -1, 1);

    // Acos(dot) returns the angle between start and end,
    // And multiplying that by percent returns the angle between
    // start and the final result.
    float delta = acos(dot);
    float theta = min(1.0f, maxAngle / delta);

    float3 relativeVec = normalize(target - current*dot); // Orthonormal basis

    float3 slerped = ((start*cos(theta)) + (relativeVec*sin(theta)));
}

推荐阅读