如何在 3d 空间中向特定方向移动点?

问题描述 投票:0回答:1

我知道如何在二维空间中的某个方向上移动一个点,如下所示:

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

但是假设

angle
变量被
pitch
yaw
roll
变量替换,我如何在 3D 空间中执行相同操作?

(顺便说一句,我正在制作光线行进算法)

math 3d raymarching
1个回答
0
投票

要使用俯仰角、偏航角和滚动角在 3D 空间中移动点,您需要将这些角度转换为方向矢量。方向向量描述了点移动的方向。

  1. 将角度转换为弧度:确保俯仰角、偏航角和横滚角均以弧度表示。如果它们以度为单位,请将其转换为弧度
  2. 计算方向矢量:根据俯仰和偏航计算方向矢量。
  3. 移动点:使用方向向量更新点的位置。
#include <cmath>

// Convert degrees to radians if needed
constexpr float DEG_TO_RAD = M_PI / 180.0f;

// Function to move a point in 3D space
void movePointIn3DSpace(float& pointX, float& pointY, float& pointZ, float pitch, float yaw, float movementSpeed) {
    // Convert angles to radians if they are in degrees
    float pitchRad = pitch * DEG_TO_RAD;
    float yawRad = yaw * DEG_TO_RAD;

    // Calculate the direction vector
    float dirX = cos(pitchRad) * sin(yawRad);
    float dirY = sin(pitchRad);
    float dirZ = cos(pitchRad) * cos(yawRad);

    // Update the point's position
    pointX += dirX * movementSpeed;
    pointY += dirY * movementSpeed;
    pointZ += dirZ * movementSpeed;
}

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

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

    // Output the new position
    printf("New position: (%f, %f, %f)\n", pointX, pointY, pointZ);

    return 0;
}

(顺便说一句,这是在 cpp 中编码的)

© www.soinside.com 2019 - 2024. All rights reserved.