簡體   English   中英

OpenGL旋轉線周圍的對象

[英]OpenGL Rotation of an object around a line

我在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圍繞軸旋轉。 一種方法是執行將旋轉軸與坐標軸中的一個對齊的變換,執行旋轉,然后反轉第一步。 如果您需要速度,可以將操作組合到一個特殊的轉換矩陣中並一步應用它們。 有一個描述在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM