3d movement around a sphere
I'm working in 3d for the first time in a long time. Basically I'm rotating a sphere and projecting x y z cords to place things on the surface based on the spheres X and Y rotation.
Heres the code im using:
#define piover180 0.017453开发者_StackOverflow社区29252f
GLfloat cosy = cos(yrot * piover180);
island[i].x = rad * sin(xrot * piover180)* cosy;
island[i].y = rad * sin(yrot * piover180);
island[i].z = rad * cos(xrot * piover180) * cosy;
Problem is the Xrot positioning works fine but the Yrot placement always draw the objects into the north and south pole so they all cross at the top, which isn't correct for rotating. I need a way to solve this. Here's a picture to help explain:
Any help would be greatly appreciated, let me know if you need any more information?
The code sample you pasted is incomplete, because you didn't show how you applied these calculations via glRotate et al. Here's how I would do this. Although you could certainly optimize it by doing the matrix calculations yourself in one step, it's likely not necessary.
// Move object out to its radius
glTranslatef(radius, 0, 0);
// Apply latitudinal rotation (aka "Yrot")
glRotatef(latitude, 0, 1, 0);
// Apply longitudinal rotation (aka "Xrot")
glRotatef(longitude, 0, 0, 1);
After that, you can do the drawing. You'll also want to wrap the whole thing in calls to glPushMatrix
and glPopMatrix
to isolate this transformation.
I ended up solving it using the Spherical Coordinate System.
Here's the code:
island[i].x = rad*sin(xrot*(PI/180))*cos(yrot*(PI/180));
island[i].y = rad*sin(xrot*(PI/180))*sin(yrot*(PI/180));
island[i].z = cos(xrot*(PI/180));
Here are the equations:
x = r sinq cosf
y = r sinq sinf
z = r cosq
r = (x2 + y2 + z2)1/2
q = tan-1(z/(x2+y2)1/2)
f = tan-1(y/x)
Just in case anyone could do with it, it's perfect for camera control or any exact 3d coord calculations you need to do.
Reference: http://electron9.phys.utk.edu/vectors/3dcoordinates.htm
精彩评论