在我的2D游戏引擎中,如果那些对象处于父子关系,则我会努力地正确渲染精灵。图片说明了问题。 我使用场景图进行渲染,并使用访问者图案进行遍历。 我希望父级的旋转仅将子级旋转到位。
//spriterenderer.cpp
// sprites are positioned & rotated around the center
GLfloat vertices[] = {
// Pos // Tex
-0.5f, 0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 1.0f, 0.0f
};
// this gets called if a GameObject has children
bool SpriteRenderer::Enter(GameObject & node)
{
...
RenderSprite(...);
// save the current modelMatrix on the stack
m_matrixStack.push_back(m_modelMatrix);
// apply transformation. I assume this is where the mistake is made
m_modelMatrix = glm::translate(m_modelMatrix, glm::vec3(node.GetLocalPosition(), 0.0f));
m_modelMatrix = glm::rotate(m_modelMatrix, node.GetLocalRotation(), glm::vec3(0.0f, 0.0f, 1.0f));
m_modelMatrix = glm::scale(m_modelMatrix, glm::vec3(node.GetLocalScale(), 1.0f));
return true;
}
// after drawing all children of a node restore the previous model matrix
bool SpriteRenderer::Leave(GameObject & node)
{
m_modelMatrix = m_matrixStack.back();
m_matrixStack.pop_back();
return true;
}
// if a node doesn't have children
bool SpriteRenderer::Visit(GameObject & node)
{
RenderSprite(...);
}
void SpriteRenderer::RenderSprite(...)
{
// save the current transformation
m_matrixStack.push_back(m_modelMatrix);
// apply model transform
m_modelMatrix = glm::translate(m_modelMatrix, glm::vec3(gameObject.GetLocalPosition(), 0.0f));
m_modelMatrix = glm::rotate(m_modelMatrix, gameObject.GetLocalRotation(), glm::vec3(0.0f, 0.0f, 1.0f));
m_modelMatrix = glm::scale(m_modelMatrix, glm::vec3(textureSize, 1.0f));
....
//restore previous transform
m_modelMatrix = m_matrixStack.back();
m_matrixStack.pop_back();
}
答案 0 :(得分:0)
我通过累加跟踪旋转找到了一个可行的解决方案。
所以,而不是
// in SpriteRenderer::Enter
m_modelMatrix = glm::rotate(m_modelMatrix, node.GetLocalRotation(), glm::vec3(0.0f, 0.0f, 1.0f));
我使用m_additiveRotation += node.GetLocalRotation();
,在SpriteRenderer :: Leave中,我再次减去该金额。
最后,在SpriteRenderer :: RenderSprite中,它更改为
m_modelMatrix = glm::translate(m_modelMatrix, glm::vec3(gameObject.GetLocalPosition(), 0.0f));
m_modelMatrix = glm::rotate(m_modelMatrix, m_additiveRotation, glm::vec3(0.0f, 0.0f, 1.0f));
m_modelMatrix = glm::rotate(m_modelMatrix, gameObject.GetLocalRotation(), glm::vec3(0.0f, 0.0f, 1.0f));
m_modelMatrix = glm::scale(m_modelMatrix, glm::vec3(textureSize, 1.0f));