Reputation: 381
I need to change my object's position with respect to camera position. I mean, my object should always be just in front of the camera. It should follow camera movements.What do I need to add my object drawing function?
Upvotes: 2
Views: 2042
Reputation: 474276
If you're using old-style fixed function matrices, the easiest way to position an object relative to the camera is to do it after removing the camera matrix from the stack. For example, you might have a matrix setup like this:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(...); //Or other camera functions.
for(/*each object*/)
{
glPushMatrix();
//Setup object matrices.
glTranslatef();
glRotatef();
//Setup object rendering.
glDrawElements(); //Draw the object
glPopMatrix();
}
Then switch it around into this:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
gluLookAt(...); //Or other camera functions.
for(/*each object*/)
{
glPushMatrix();
//Setup object matrices.
glTranslatef();
glRotatef();
//Setup object rendering.
glDrawElements(); //Draw the object
glPopMatrix();
}
glPopMatrix(); //Remove camera matrix. MODELVIEW is now identity.
for(/*each camera-relative object*/)
{
glPushMatrix();
//Setup object matrices.
glTranslatef();
glRotatef();
//Setup object rendering.
glDrawElements(); //Draw the object
glPopMatrix();
}
If you're using shaders, this is even easier. If you have a matrix stack, just do the same stack-based operation as you see here. If you're doing something else to build your matrices, just don't factor the camera matrix into the transform.
Upvotes: 2
Reputation: 7773
Your object position should then always be at:
desiredPosition = cameraPosition + cameraDirection * offset;
Upvotes: 1