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

问题描述 投票:1回答:1

我一直在使用这个GameObject(它使用Box2D)和Renderer2D类已经有一段时间了,我没有遇到任何问题。直到我决定添加旋转对象的选项。所有工作都很好(或似乎是)用方框2D,但是在屏幕上看到的对象在错误的轴上移动,在向上移动时变小,在向下移动时移动得更大(或者越来越远离相机)。

我添加到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。试图改变视图矩阵的远近值,仍然是相同的结果。

c++ opengl box2d
1个回答
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];

仍然没有得到我想要的旋转,但至少其他功能工作。

© www.soinside.com 2019 - 2024. All rights reserved.