我知道如何在二维空间中的某个方向上移动一个点,如下所示:
pointX += sin(angle) * movementSpeed;
pointY += cos(angle) * movementSpeed;
但是假设
angle
变量被 pitch
、yaw
和 roll
变量替换,我如何在 3D 空间中执行相同操作?
(顺便说一句,我正在制作光线行进算法)
要使用俯仰角、偏航角和滚动角在 3D 空间中移动点,您需要将这些角度转换为方向矢量。方向向量描述了点移动的方向。
#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 中编码的)