OpenGL围绕一条线旋转对象

我在OpenGL和C ++编程。 我知道1条线上有2个点(一条对角线),并希望围绕该对角线旋转一个物体。 我怎么能这样做呢? 我知道如何使用glrotatef围绕x,y或z轴旋转它,但我不确定这一点。


glRotate的x,y和z参数可以指定任意轴,而不仅仅是x,y和z轴。 要找到穿过线的轴,只需要减去线的端点即可得到轴矢量:如果两点是(x1, y1, z1)(x2, y2, z2) ,则需要的轴是(x2-x1, y2-y1, z2-z1)

编辑:正如@chris_l指出的,只有当这条线穿过原点时,这才起作用。 如果不是,则首先应用(-x1, -y1, -z1)以便该线穿过原点,然后应用上述旋转,并将其翻译回(x1, y1, z1)


嘿,做一些四元数/矢量数学怎么样? =)我已经在我的Vector类中使用小“补丁”

double NumBounds(double value)
{
    if (fabs(value) < (1 / 1000000.0f))
        return 0; else
            return value;
}

class Vector
{
    private:
        double x, y, z;

    public:
        Vector(const Vector &v)
        {
            x = NumBounds(v.x); y = NumBounds(v.y); z = NumBounds(v.z);
        }

        Vector(double _x, double _y, double _z)
        {
            x = NumBounds(_x); y = NumBounds(_y); z = NumBounds(_z);
        }

        Vector Normalize()
        {
            if (Length() != 0)
                return Vector(x / Length(), y / Length(), z / Length()); else
                    return *this;
        }

        double operator[](unsigned int index) const
        {
            if (index == 0)
                return NumBounds(x); else
            if (index == 1)
                return NumBounds(y); else
            if (index == 2)
                return NumBounds(z); else
                    return 0;
        }

        void operator=(const Vector &v)
        {
            x = NumBounds(v.x); y = NumBounds(v.y); z = NumBounds(v.z);
        }

        Vector operator+(const Vector &v)
        {
            return Vector(x + v.x, y + v.y, z + v.z);
        }

        Vector operator-(const Vector &v)
        {
            return Vector(x - v.x, y - v.y, z - v.z);
        }

        double operator*(const Vector &v)
        {
            return NumBounds((x * v.x) + (y * v.y) + (z * v.z));
        }

        Vector operator*(double s)
        {
            return Vector(x * s, y * s, z * s);
        }

        Vector DotProduct(const Vector &v)
        {
            double k1 = (y * v.z) - (z * v.y);
            double k2 = (z * v.x) - (x * v.z);
            double k3 = (x * v.y) - (y * v.x);

            return Vector(NumBounds(k1), NumBounds(k2), NumBounds(k3));
        }

        Vector Rotate(Vector &axis, double Angle)
        {
            Vector v = *this;

            return ((v - axis * (axis * v)) * cos(angle)) + (axis.DotProduct(v) * sin(angle)) + (axis * (axis * v));
        }
};

使用这个类,您可以轻松地围绕任何其他的矢量旋转任何矢量:

Vector a(1.0f, 0.0f, 0.0f), b(0.0f, 1.0f, 0.0f), c(0.0f, 0.0f, 0.0f);

c = a.Rotate(b, M_PI / 2.0f); // rotate vector a around vector b for 90 degrees (PI / 2 radians): should be Vector(0, 0, 1);

glrotate会绕轴旋转。 一种方法是执行将旋转轴与坐标轴之一对齐的变换,执行旋转,然后颠倒第一步。 如果您需要速度,您可以将这些操作组合成一个特殊的变换矩阵,并将它们一步应用。 这里有一个描述。

链接地址: http://www.djcxy.com/p/81831.html

上一篇: OpenGL Rotation of an object around a line

下一篇: OpenGL rotating a camera around a point