# Cylinder between two points (OpenGL C++)

4th December 2010Whilst working on one of my projects this year for uni I was looking for some code to draw a cylinder between two points (using OpenGL). There were a couple of solutions out there, but they weren’t that great.

I couldn’t find one that worked reliably and simply (without lots of different if statements trying to catch different cases). Anyway, after a bit of thought I knocked this one out. It’s actually a lot simpler than you think…which is probably why people haven’t bothered to post it.

Anyway…enjoy some pseudo code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Vector3D a, b; (the two points you want to draw between) // This is the default direction for the cylinders to face in OpenGL Vector3D z = Vector3D(0,0,1);Â Â Â Â Â Â Â Â // Get diff between two points you want cylinder along Vector3D p = (a - b);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â // Get CROSS product (the axis of rotation) Vector3D t = CROSS_PRODUCT (z , p); // Get angle. LENGTH is magnitude of the vector double angle = 180 / PI * acos ((DOT_PRODUCT(z, p) / p.LENGTH()); glTranslated(b.x,b.y,b.z); glRotated(angle,t.x,t.y,t.z); gluQuadricOrientation(YourQuadric,GLU_OUTSIDE); gluCylinder(YourQuadric, RADIUS, RADIUS, p.LENGTH(), SEGS1, SEGS2); |

Hope that helps someone out there.