You need basis vectors for this (which can be encoded into transform matrix).
So let assume you got:
p0[3],p1[3]
- 3D center points (x,y,z)
of your cylinder bases
r
- radius
To construct transform matrix you need
O[3]
- origin position
X[3],Y[3],Z[3]
- basis vectors
So you can exploit cross product to get perpendicular vectors:
O = p0;
Z = p1-p0;
Y = (1.0,0.0,0.0);
if (|dot(Y,Z)/|Z||>0.75) Y = (0.0,1.0,0.0); // this just make sure Z and Y are not parallel
X = cross(Y,Z);
Y = cross(Z,X);
X = r*X/|X|;
Y = r*Y/|Y|;
Now construct your 4x4 transform matrix M
or use the X,Y,Z,O
directly to compute the vertexes:
base0:
x=cos(a);
y=sin(a);
z=0.0;
base1:
x=cos(a);
y=sin(a);
z=1.0;
Where a = <0.0,2.0*PI>
is angle. XY
plane is parallel to bases and z is cylinder axis. To convert these (x,y,z)
to World coordinates use:
(x',y',z') = M * (x,y,z)
Which can be done natively in OpenGL by using M
as part of GL_MODELVIEW
or do this instead:
x' = O[0] + x*X[0] + y*Y[0] + z*Z[0];
y' = O[1] + x*X[1] + y*Y[1] + z*Z[1];
z' = O[2] + x*X[2] + y*Y[2] + z*Z[2];
Take a look at related QAs:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…