如何在3d场景中旋转单个对象?

时间:2013-10-28 12:47:41

标签: c++ matrix opengl-4

我想在3d场景中旋转对象。在下面的代码中,我简单地旋转了WorldMatrix。但是如果场景包含2个对象而不是1个呢?如果我旋转WorldMatrix,两者都会旋转(以奇怪的方式)。如何在不改变任何其他模型的情况下旋转场景中的单个对象?

// 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();

3 个答案:

答案 0 :(得分:2)

为每个对象设置一个“对象矩阵”,在渲染该对象之前将其推送,然后弹出。有了这个,你可以修改每个对象的对象矩阵,以便旋转它(或以任何其他方式转换它)。

答案 1 :(得分:2)

您希望渲染的每个“对象”至少应包含其自己的包含旋转和位置信息的4x4矩阵。这样,如果您只想旋转一个对象,只需编辑它自己的个人矩阵即可。

管理所有这些矩阵运算的最简单方法是通用matrix stack

不幸的是,内置的OpenGL矩阵堆栈功能(glPushglPop等)与大多数旧的固定功能管道一起被弃用。但幸运的是,一位StackOverflow用户发布了一个简单的矩阵堆栈:Replacing glPush/PopMatrix

答案 2 :(得分:0)

首先,您应该绘制对象以进行旋转。

void DrawObject(Object* object)
{
    glTranslate(object->y);
    glRotate(object->rotationY, roll, yaw , pitch);
}