Question

I want to rotate an object in a 3d scene. In the code below I simply rotated the WorldMatrix. But what if the scene contained 2 objects instead of one? If I rotated the WorldMatrix both would rotate (in a weird way). How should I rotate a single object in a scene without altering any other model?

// Clear the buffers to begin the scene.
m_OpenGL->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);

// Generate the view matrix based on the camera's position.
m_Camera->Render();

// Get the world, view, and projection matrices from the opengl and camera objects.
m_OpenGL->GetWorldMatrix(worldMatrix);
m_Camera->GetViewMatrix(viewMatrix);
m_OpenGL->GetProjectionMatrix(projectionMatrix);

// Get the light properties.
m_Light->GetDirection(lightDirection);
m_Light->GetDiffuseColor(diffuseLightColor);
m_Light->GetAmbientLight(ambientLight);

// Rotate the world matrix by the rotation value so that the object will spin.
m_OpenGL->MatrixRotationY(worldMatrix, rotation);

// Set the light shader as the current shader program and set the matrices that it will use for rendering.
m_LightShader->SetShader(m_OpenGL);
m_LightShader->SetShaderParameters(m_OpenGL, worldMatrix, viewMatrix, projectionMatrix, 0, lightDirection, diffuseLightColor, ambientLight);

// Render the model using the light shader.
m_Model->Render(m_OpenGL);

// Present the rendered scene to the screen.
m_OpenGL->EndScene();
Was it helpful?

Solution

Each "object" that you wish to render should include, at minimum, its own 4x4 matrix containing rotation and position information. That way, if you want to rotate only a single object, you just edit it's own personal matrix.

The easiest way to manage all of these matrix operations is a general purpose matrix stack.

Unfortunately for you, the built-in OpenGL matrix stack functionality (glPush, glPop, etc.) is deprecated along with most of the old fixed-function pipeline. But fortunately for you, a fellow StackOverflow user posted a bare-bones matrix stack: Replacing glPush/PopMatrix.

OTHER TIPS

Have an "object matrix" for each object, which you push before rendering that object and pop afterwards. With this in place, you can modify the object matrix of each object in order to rotate it (or transform it in any other way).

First of all you should draw your object to rotate.

void DrawObject(Object* object)
{
    glTranslate(object->y);
    glRotate(object->rotationY, roll, yaw , pitch);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top