【问题标题】:3D vector rotation in C++ [closed]C ++中的3D矢量旋转[关闭]
【发布时间】:2017-02-24 01:42:31
【问题描述】:

我尝试使用 Rodrigues 的旋转公式(Rodrigues' rotation formula):

vector3 vector3::rotate(const vector3 &axis, double theta) const
{
    double cos_theta = cos(theta);
    double sin_theta = sin(theta);
    vector3 rotated = *this*cos_theta + (axis^*this)*sin_theta + axis*(axis*(*this))*(1 - cos_theta);
    return rotated;
}

但它似乎无法正常工作。我不知道我在这里缺少什么,任何帮助将不胜感激。

编辑

这些是我使用的运算符:

vector3 operator*(double) const; //multiplication by scalar
friend vector3 operator*(double, const vector3&); //multiplication by scalar
double operator*(const vector3&) const; //dot product
vector3 operator^(const vector3&) const; //cross product

并且它们已经过测试(它们可以正常工作)。

【问题讨论】:

  • axis^*this 您似乎重载了我们没有定义的运算符...恐怕我们无法为您提供太多帮助(除非错误出现在我们无法做到的那一行肯定的)
  • @Borgleader 抱歉,我编辑了我的问题。
  • @Eutherpy 您介意发布minimal reproducible example 并告诉我们到底出了什么问题(输入、输出、预期输出)。
  • 轴是否应该是单位向量?
  • 可能很愚蠢的问题:theta 是度数还是弧度?此外,将来拥有专用的 dotcross 函数可能会更容易,因此其他人(或未来的你)不必查看 *^ 可能在做什么。

标签: c++ vector 3d rotation


【解决方案1】:

这可能会有所帮助:How do axis-angle rotation vectors work and how do they compare to rotation matrices?

另外,您可能不想听到这个消息,但GLM 可能会让您的生活更轻松。您的运算符重载看起来非常棘手。

这是我的实现尝试...

#include <iostream>
#include <cmath>

#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>

// v: a vector in 3D space
// k: a unit vector describing the axis of rotation
// theta: the angle (in radians) that v rotates around k
glm::dvec3 rotate(const glm::dvec3& v, const glm::dvec3& k, double theta)
{
    std::cout << "Rotating " << glm::to_string(v) << " "
              << theta << " radians around "
              << glm::to_string(k) << "..." << std::endl;

    double cos_theta = cos(theta);
    double sin_theta = sin(theta);

    glm::dvec3 rotated = (v * cos_theta) + (glm::cross(k, v) * sin_theta) + (k * glm::dot(k, v)) * (1 - cos_theta);

    std::cout << "Rotated: " << glm::to_string(rotated) << std::endl;

    return rotated;
}

int main()
{
    glm::dvec3 v(1.0, 0.0, 0.0);
    glm::dvec3 k(0.0, 0.0, 1.0);
    double theta = M_PI; // 180.0 degrees

    // Rotate 'v', a unit vector on the x-axis 180 degrees
    // around 'k', a unit vector pointing up on the z-axis.
    glm::dvec3 rotated = rotate(v, k, theta);

    return 0;
}

返回...

Rotating dvec3(1.000000, 0.000000, 0.000000) 3.14159 radians around dvec3(0.000000, 0.000000, 1.000000)...
Rotated: dvec3(-1.000000, 0.000000, 0.000000)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2019-02-03
    • 2022-08-21
    • 1970-01-01
    相关资源
    最近更新 更多