PDA

View Full Version : use gluUnproject to move object, and it doesn't ..



blldw
06-29-2009, 08:17 AM
// my code is as follows, and you will found the box doesn't
// move with mouse.
// It seems that the mouse moves faster than the box.
// I wonder why it would be like that.

#include <gl/glut.h>

static double xmov = 0.0;
static double ymov = 0.0;

void reshape(GLsizei width, GLsizei height);
void display();
void motion(int x, int y);
void init();

int main(int argc, char *argv[])
{
glutInit(&amp;argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(800, 600);
glutCreateWindow("translation test...");

glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMotionFunc(motion);
init();
glutMainLoop();

return 0;
}

void reshape(GLsizei width, GLsizei height)
{
if (height == 0)
height = 1;

glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
gluPerspective(60.0, (GLdouble)width / (GLdouble)height, 5.0, 105.0);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void display()
{
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
glTranslated(xmov, ymov, -55.0);

// draw a cylinder
glColor4f(0.5, 0.5, 0.5, 0.5);
glutSolidCube(20.0);

glutSwapBuffers();
}

void motion(int x, int y)
{
static int xLast = x;
static int yLast = y;

double modelMtx[16] = { 0.0 }, projMtx[16] = { 0.0 };
int vp[4] = { 0 };
double oriX, oriY, oriZ, newX, newY, newZ;

glGetDoublev(GL_MODELVIEW_MATRIX, modelMtx);
glGetDoublev(GL_PROJECTION_MATRIX, projMtx);
glGetIntegerv(GL_VIEWPORT, vp);
// use gluUnproject to get the space location corresponding to mouse location
gluUnProject(xLast, vp[3] - yLast, 0.5, modelMtx, projMtx, vp, &amp;oriX, &amp;oriY, &amp;oriZ);
gluUnProject(x, vp[3] - y, 0.5, modelMtx, projMtx, vp, &amp;newX, &amp;newY, &amp;newZ);

xmov += newX - oriX;
ymov += newY - oriY;

xLast = x, yLast = y;

glutPostRedisplay();
}

void init()
{
glClearColor(0.75f, 0.75f, 0.75f, 1.0f);
glShadeModel(GL_SMOOTH);
}

dletozeun
06-29-2009, 09:46 AM
So what's the problem with gluUnproject? Just draw your object at the world coordinates you get.

blldw
06-30-2009, 01:59 AM
okey, the problem is the object doesn't move along with mouse closely if you execute the code above. However, the problem is resolved. Thanks for regarding.