【问题标题】:OpenGl draw a cylinder with 2 points glRotatedOpenGL用2个点画一个圆柱体 glRotated
【发布时间】:2018-02-15 08:21:46
【问题描述】:

我想画一个从 a 点开始的圆柱体,它指向我认为关键在第一个 glRotated 中,但这是我第一次使用 openGL a 和 b 是 btVector3

glPushMatrix();
glTranslatef(a.x(), a.y(), a.z());
glRotated(0, b.x(), b.y(), b.z());
glutSolidCylinder(.01, .10 ,20,20);
glPopMatrix();

有什么建议吗??

【问题讨论】:

    标签: c++ visual-studio opengl glrotate


    【解决方案1】:

    根据glutsolidcylinder(3) - Linux man page

    glutSolidCylinder() 绘制一个带阴影的圆柱体,其底面的中心位于原点,轴沿正 z 轴。

    因此,您必须分别准备转换:

    • 将圆柱体的中心移至原点(即 (a + b) / 2)
    • 将圆柱的轴(即b - a)旋转为z轴。

    glRotatef() 的用法似乎被误解了,还有:

    • 第一个值是旋转角度,以度为单位
    • 第2、3、4个值分别是旋转轴的x、y、z。

    这将导致:

    // center of cylinder
    const btVector3 c = 0.5 * (a + b);
    // axis of cylinder
    const btVector3 axis = b - a;
    // determine angle between axis of cylinder and z-axis
    const btVector3 zAxis(0.0, 0.0, 1.0);
    const btScalar angle = zAxis.angle(axis);
    // determine rotation axis to turn axis of cylinder to z-axis
    const btVector3 axisT = zAxis.cross(axis).normalize();
    // do transformations
    glTranslatef(c.x(), c.y(), c.z());
    if (axisT.norm() > 1E-6) { // skip this if axis and z-axis are parallel
      const GLfloat radToDeg = 180.0f / 3.141593f; 
      glRotatef(angle * radToDeg, axisT.x(), axisT.y(), axisT.z());
    }
    glutSolidCylinder(0.1, axis.length(), 20, 20);
    

    我写这段代码是出于心智(使用我以前从未使用过的btVector3 的文档)。因此,请把这个和一粒盐一起吃。 (可能需要调试。)

    所以,请记住以下几点:

    1. 文档。没有提到 btVector3::angle() 是返回角度还是弧度——我假设是弧度。

    2. 在编写此类代码时,我经常会不小心翻转一些东西(例如,旋转到相反的方向)。这样的东西,我一般是在调试的时候修复的,对于上面的示例代码,这可能是必要的。

    3. 如果 (b - a) 已经沿正或负 z 轴,则 (b - a) × (0, 0, 1) 将产生一个 0 向量。不幸的是,医生。 btVector3::normalize() 没有提到应用于 0 向量时会发生什么。如果在这种情况下抛出异常,当然必须添加额外的检查。

    【讨论】:

    • 它就像一个魅力。我希望圆柱体从 a 点开始,所以我使用 a 位置作为 translate 的第一个参数。还有角度所以不需要转换。非常感谢!!!!!!
    【解决方案2】:

    自旋转 0 度以来,您的旋转不会做任何事情。

    您希望轴 z 指向 b。 为此,您需要计算 z 轴 (0,0,1) 和 norm(b - a) 之间的角度(即arccos(z dot norm(b - a))),并且您需要围绕 z 轴和 b 之间的叉积旋转该量- 一种。您的向量库应该已经实现了这些方法(点积和叉积)。

    norm(x) 是 x 的归一化版本,长度为 1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      相关资源
      最近更新 更多