ShaderToy中如何让点沿着3D空间中的某个方向运动?

Number of views 29

我知道如何在二维空间中沿着某个方向运动,比如下面的代码:

pointX += sin(angle) * movementSpeed;
pointY += cos(angle) * movementSpeed;

但是,如果代表角度的变量被替换为俯仰角(pitch)、偏航角(yaw)和滚转角(roll),我该如何在三维空间中沿着某个方向运动?

1 Answers

要使用俯仰角(pitch)、偏航角(yaw)和翻滚角(roll)在3D空间中移动一个点,你需要将这些角度转换成方向向量。方向向量描述了点将要移动的方向。

  1. 将角度转换为弧度:确保你的俯仰角、偏航角和翻滚角是以弧度为单位的。如果它们是以度为单位的,那么需要将它们转换为弧度。
  2. 计算方向向量:基于俯仰角和偏航角计算方向向量。
  3. 移动点:使用方向向量来更新点的位置。

以C++代码来说明:

#include <cmath>

// 将角度转为弧度
constexpr float DEG_TO_RAD = M_PI / 180.0f;

// 函数的作用是在3d空间中移动一个点
void movePointIn3DSpace(float& pointX, float& pointY, float& pointZ, float pitch, float yaw, float movementSpeed) {
    // 转为弧度
    float pitchRad = pitch * DEG_TO_RAD;
    float yawRad = yaw * DEG_TO_RAD;

    // 计算方向
    float dirX = cos(pitchRad) * sin(yawRad);
    float dirY = sin(pitchRad);
    float dirZ = cos(pitchRad) * cos(yawRad);

    // 更新点的位置
    pointX += dirX * movementSpeed;
    pointY += dirY * movementSpeed;
    pointZ += dirZ * movementSpeed;
}


int main() {
    float pointX = 0.0f, pointY = 0.0f, pointZ = 0.0f;
    float pitch = 30.0f;  // 角度
    float yaw = 45.0f;    // 角度
    float movementSpeed = 1.0f;

    movePointIn3DSpace(pointX, pointY, pointZ, pitch, yaw, movementSpeed);

    // 输出新的位置
    printf("New position: (%f, %f, %f)\n", pointX, pointY, pointZ);

    return 0;
}