b2 Shape 等于 0xCDCDCDCD,在 Create Fixture 时抛出异常

b2Shape is equal to 0xCDCDCDCD and thows an exception at Create Fixture

我正在按照 http://box2d.org/manual.pdf 上的手册尝试更好地理解 Box2D 的工作原理,但我 运行 遇到了问题。当我打电话 m_body->CreateFixture 它在尝试访问 fixtureDef->shape 时抛出异常,因为 fixtureDef->shape 是 0xCDCDCDCD。我很困惑,因为我还在学习Box2D,如果有人能帮忙解释一下,我会很高兴的。

这里有一些重要的代码片段需要了解 PhysicsEngine.h:

class PhysicsGround{
private:
    b2Body* m_body;
    b2Fixture* m_fixture;
    b2PolygonShape m_shape;

public:
    void init(glm::vec2 pos, glm::vec2 size, b2World* world);

    b2Body* getBody();
    void setBody(b2Body* body);

    b2Fixture* getFixture();
};

class PhysicsEngine
{
private:
    ICMEM::StackAllocator m_stackAlloc;

    std::vector<PhysicsSprite*> m_physObjs;

    b2World* m_world;
    b2Vec2 m_gravity;

public:
    PhysicsEngine() {}
    void init(float gravX, float gravY);
    void shutDown();

    void addPhysicsObject(PhysicsSprite* sprite);
    void addGround(glm::vec2 pos, glm::vec2 size);
    void setGravity(float gravX, float gravY);
    void update(double dt);

    b2World* getWorld() { return m_world; }
};

这是来自 PhysicsEngine.cpp 的一些重要信息:

void PhysicsEngine::init(float gravX, float gravY) {
    m_stackAlloc.init(200000000);
    m_world = (b2World*)m_stackAlloc.allocAligned(sizeof(b2World), alignof(b2World));
    m_world = new(m_world)b2World(b2Vec2(gravX, gravY));
}

void PhysicsEngine::addGround(glm::vec2 pos, glm::vec2 size) {
    PhysicsGround* physicsGround = (PhysicsGround*)m_stackAlloc.allocAligned(sizeof(PhysicsGround), alignof(PhysicsSprite));
    physicsGround->init(pos, size, m_world);
}

void PhysicsGround::init(glm::vec2 pos, glm::vec2 size, b2World* world) {
    b2BodyDef groundBodyDef;
    groundBodyDef.position.Set(pos.x, pos.y);
    m_body = world->CreateBody(&groundBodyDef);

    m_shape.SetAsBox(size.x / 2.0f, size.y / 2.0f);
    m_fixture = m_body->CreateFixture(&m_shape, 0.0f); // Exception thrown here
}

您的对象中有未初始化的值。这会在非调试版本中创建随机值,在这种情况下,模式 0xCDCDCDCD 是这些未初始化值的典型 Visual Studio 调试值。

您可能想要使用 C++11 初始化功能,因为您没有提供自定义构造函数。例如:

class PhysicsGround{
private:
    b2Body* m_body{nullptr};
    b2Fixture* m_fixture{nullptr};
    b2PolygonShape m_shape;
//
};