1

I get the corrected screen coordination (0,0 at Left Bottom):

GLint realy;
realy = winHeight - (GLint) y - 1;
screen.x = (float)x;
screen.y = (float)realy;

Then I get the world at zNear and zFar:

worldNear = glm::unProject(glm::vec3(screen.x, screen.y, 0.0), viewMatrix, projectionMatrix, glm::vec4(0.0f, 0.0f, winWidth, winHeight));
worldFar = glm::unProject(glm::vec3(screen.x, screen.y, 1.0), viewMatrix, projectionMatrix, glm::vec4(0.0f, 0.0f, winWidth, winHeight));

but I setup my Perspective projection like this, so I know the zFar and zNear and I'm not sure if the above code is necessary: glm::perspective(fovy, 1.0f * winWidth/winHeight, zNear, zFar); (we need to get zNear and zFar by X, Y, Z -- so we need to unproject near and far)

Also, detect Zdepth buffer like this:

GLfloat depth;
glReadPixels(screen.x, screen.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);

and pixel colors like this:

GLubyte pixel[3];
glReadBuffer( GL_BACK );
glReadPixels(screen.x, screen.y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, (void *)pixel);

Problem is here: I can get the World X,Y,Z, but I need to normalize coordination, so I can move objects smoothly by mouse, How?

glm::vec4 normalizePoint = ** ??? **
world.x = normalizePoint.x;
world.y = normalizePoint.y;
world.z = normalizePoint.z;

(currently my world coord is either too far or too near, that's the problem)

Edit: I find the answer in the first question here:

iPhone OpenGL : Using gluUnProject (port) and detecting clicking on an object

I need ray-object collision, it works now!!

Community
  • 1
  • 1
xxx
  • 554
  • 8
  • 17
  • 1
    What do you mean by normalize? Typically that refers to dividing a vector by a scalar to put it in a standard form (most often unit length). Your code looks okay but I question why you're reading the back buffer and z-buffer when you can just do ray-object collision directly with your world positions. – Ron Warholic Jan 26 '12 at 23:49
  • 1
    The problem is that we don't understand what you're asking for or what you're trying to do. Your use of terminology like "normalize" is non-standard and confusing, for example. – Nicol Bolas Jan 26 '12 at 23:56

1 Answers1

0

Project the 2D vector you have in screen space for the move (e.g. (20,0) is 20 pixels right) into world space at the same depth as the object you're moving.

The 'same depth' as the object is found by projecting the object position into screen space through your view and projection matrices.

glm::vec3 addThisToYourObjectPosition = glm::unProject(glm::vec3(screenMove.x, screenMove.y, objectProjectedZ), viewMatrix, projectionMatrix, glm::vec4(0.0f, 0.0f, winWidth, winHeight));
Marvin Pinto
  • 30,138
  • 7
  • 37
  • 54
Slagh
  • 342
  • 2
  • 8