我知道如何在二维空间中沿着某个方向运动,比如下面的代码:
pointX += sin(angle) * movementSpeed;
pointY += cos(angle) * movementSpeed;
但是,如果代表角度的变量被替换为俯仰角(pitch)、偏航角(yaw)和滚转角(roll),我该如何在三维空间中沿着某个方向运动?
我知道如何在二维空间中沿着某个方向运动,比如下面的代码:
pointX += sin(angle) * movementSpeed;
pointY += cos(angle) * movementSpeed;
但是,如果代表角度的变量被替换为俯仰角(pitch)、偏航角(yaw)和滚转角(roll),我该如何在三维空间中沿着某个方向运动?
要使用俯仰角(pitch)、偏航角(yaw)和翻滚角(roll)在3D空间中移动一个点,你需要将这些角度转换成方向向量。方向向量描述了点将要移动的方向。
以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;
}