顶点相对于法线的位置

问题描述 投票:5回答:2

在曲面着色器中,给定世界上的上轴(其他也是),一个世界空间位置和世界空间中的法线,我们如何将世界空间位置旋转到法线的空间?

也就是说,给定一个上轴向量和一个非正交的目标上轴向量,我们如何通过旋转其上轴向量来变换位置?

我需要这样做,这样我就可以得到只受对象旋转矩阵影响的顶点位置,我的旋转矩阵是 不要 有权访问。

这是我想做的图形化。

  • Up is the world up vector
  • 目标是世界空间常态
  • Pos是任意的

图是二维的,但我需要解决的是三维空间的问题。

vector diagram

unity3d transform hlsl cg geometry-surface
2个回答
0
投票

看来你是想旋转 姿势 以同样的旋转方式改变 新上.

使用发现的旋转矩阵 此处,我们可以旋转 姿势 使用以下代码。这将在曲面函数或补充顶点函数中工作,取决于你的应用程序。

// Our 3 vectors
float3 pos;
float3 new_up;
float3 up = float3(0,1,0);

// Build the rotation matrix using notation from the link above
float3 v = cross(up, new_up);
float s = length(v);  // Sine of the angle
float c = dot(up, new_up); // Cosine of the angle
float3x3 VX = float3x3(
    0, -1 * v.z, v.y,
    v.z, 0, -1 * v.x,
    -1 * v.y, v.x, 0
); // This is the skew-symmetric cross-product matrix of v
float3x3 I = float3x3(
    1, 0, 0,
    0, 1, 0,
    0, 0, 1
); // The identity matrix
float3x3 R = I + VX + mul(VX, VX) * (1 - c)/pow(s,2) // The rotation matrix! YAY!

// Finally we rotate
float3 new_pos = mul(R, pos);

这是在假设 新上 是正常化的。

如果 "目标向上正常 "是一个常数,则计算出的 R 可以(也应该)每帧只发生一次。我建议在CPU端进行计算,并将其作为一个变量传递到着色器中。为每个顶点帧计算它的成本很高,考虑一下你真正需要的是什么。

如果你的 姿势 是一个向量-4,只需对前三个元素进行上述操作即可,第四个元素可以保持不变(反正在这种情况下,它没有任何意义)。

我远离了可以运行着色器代码的机器,所以如果我在上面犯了什么语法错误,请原谅我。


-3
投票

没有测试过,但应该可以输入一个起始的 point 和一个 axis. 那你要做的就是改变 procession 这是一个沿圆周的归一化(0-1)浮动,你的点会相应更新。

using UnityEngine;
using System.Collections;

public class Follower : MonoBehaviour {

    Vector3 point;
    Vector3 origin = Vector3.zero;
    Vector3 axis = Vector3.forward;
    float distance;
    Vector3 direction;
    float procession = 0f;  // < normalized

    void Update() {
        Vector3 offset = point - origin;

        distance = offset.magnitude;
        direction = offset.normalized;

        float circumference = 2 * Mathf.PI * distance;

        angle = (procession % 1f) * circumference;

        direction *= Quaternion.AngleAxis(Mathf.Rad2Deg * angle, axis);
        Ray ray = new Ray(origin, direction);

        point = ray.GetPoint(distance);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.