更改对象的原点会使它在不同的轴上移动

时间:2019-03-20 19:37:34

标签: c++ opengl box2d

我已经使用这个GameObject(利用Box2D)和Renderer2D类已有一段时间了,但我没有遇到任何问题。直到我决定添加旋转对象的选项。在2D框上,所有功能都可以正常工作(或似乎可以正常工作),但是在屏幕上看到的对象在错误的轴上移动,向上移动时对象变小,向下移动(或距离相机更近,更远)时对象变大。 / p>

我添加到Renderer2D脚本的仅有的三行是:

    model = math::translate(model, iVec3(0.5f * size.x, 0.5f * size.y, 0.0f));
    model = math::rotate(model, rotation, iVec3(0.0f, 0.0f, 1.0f));
    model = math::translate(model, iVec3(-0.5f * size.x, -0.5f * size.y, 0.0f));

如果我只删除这些行,那么一切正常,但是我希望对象旋转以便不能删除它们。

这是整个渲染功能:

void Renderer2D::Render(Texture & texture, iVec2 position, iVec2 size, float rotation, Color color, iVec2 tiling) {
    this->shader.Use();
    iMat4x4 model;

    model = math::translate(model, iVec3(position, 0.0f));

    model = math::translate(model, iVec3(0.5f * size.x, 0.5f * size.y, 0.0f));
    model = math::rotate(model, rotation, iVec3(0.0f, 0.0f, 1.0f));
    model = math::translate(model, iVec3(-0.5f * size.x, -0.5f * size.y, 0.0f));

    model = math::scale(model, iVec3(size, 1.0f));

    this->shader.SetMatrix4("model2D", model);
    this->shader.SetVector3f("spriteColor", iVec3(color.r, color.g, color.b));
    this->shader.SetVector2f("tiling", tiling);

    glActiveTexture(GL_TEXTURE0);
    texture.Bind();

    glBindVertexArray(this->QuadVAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
    glBindVertexArray(0);
}

我用Box2D的Velocity变量移动GameObject,如下所示:

float horizontal, vertical;
        if (Input::GetKeyDown(Input::Key.A) || Input::GetKeyDown(Input::Key.D)) {
            if (Input::GetKeyDown(Input::Key.A))
                horizontal = -1;
            else if (Input::GetKeyDown(Input::Key.D))
                horizontal = +1;
        }
        else horizontal = 0;

        if (Input::GetKeyDown(Input::Key.W) || Input::GetKeyDown(Input::Key.S)) {
            if (Input::GetKeyDown(Input::Key.W))
                vertical = -1;
            else if (Input::GetKeyDown(Input::Key.S))
                vertical = +1;
        }
        else vertical = 0;

        Rigidbody2D->Velocity = iVec2(horizontal, vertical) * speed;

我真的已经尝试了所有方法,但仍然不知道是相机问题,渲染器还是Box2D。尝试更改视图矩阵的远近值,结果仍然相同。

1 个答案:

答案 0 :(得分:0)

解决了主要问题,在控制台上打印矩阵后,我意识到第四列已从x y 0 1替换为0 x 0 y。

更改了代码:

model = math::translate(model, iVec3(0.5f * size.x, 0.5f * size.y, 0.0f));
model = math::rotate(model, rotation, iVec3(0.0f, 0.0f, 1.0f));
model = math::translate(model, iVec3(-0.5f * size.x, -0.5f * size.y, 0.0f));

到此完成!

iMat4x4 tempModel;
iMat4x4 tempModel2;


tempModel = math::translate(tempModel, iVec3(0.5f * size.x, 0.5f * size.y, 0.0f));
model[3].z = model[3].w = 0;
model[3] = model[3] + tempModel[3];

model = math::rotate(model, rotation, iVec3(0.0f, 0.0f, 1.0f));

tempModel2 = math::translate(tempModel2, iVec3(-0.5f * size.x, -0.5f * size.y, 0.0f));
model[3].z = model[3].w = 0;
model[3] = model[3] + tempModel2[3];

仍然没有得到我想要的轮换,但是至少其他功能起作用了。