jeremy d.
jeremy d.

Reputation: 11

Destroy a Box2D Body - read acces violation error

i trying to destroy a Box2D body, but every time i'm trying to destroy it, my game is crashing, because of a read acces violation error.

Code to delete the body:

if (event.mouseButton.button == sf::Mouse::Left) {
    if (((chunk.getChunkPosition().x + MAX_CHUNK_WIDTH * 16 > block.x * 16)
      && (block.x * 16 >= chunk.getChunkPosition().x))
      && ((chunk.getChunkPosition().y + MAX_CHUNK_HEIGHT * 16 > block.y * 16)
      && (block.y * 16 >= chunk.getChunkPosition().y)))
    {
        chunk.blockPhysic[block.x][block.y]->setCreatedState(false);
        world.getBWorld()->DestroyBody(chunk.blockPhysic[block.x][block.y]->getBody());
    }
}

Code to create the body/block:

BlockPhysic::BlockPhysic(b2World* world, const sf::Vector2f& _position, const int& _textureKeyID, const sf::IntRect& _textRect, sf::Vector2f _size, bool _dynamicBody)
{
    b2BodyDef bBodyDef;
    dynamicBody = _dynamicBody;
    bBodyDef.type = _dynamicBody == true ? b2_dynamicBody : b2_staticBody;
    bBodyDef.position.Set(_position.x, _position.y);
    rBody = world->CreateBody(&bBodyDef);

    b2PolygonShape bShape;
    bShape.SetAsBox(_size.x / 2, _size.y / 2);
    b2FixtureDef bFixtureDef;
    bFixtureDef.shape = &bShape;
    bFixtureDef.density = 0.0f;
    bFixtureDef.friction = 0.0f;
    rFixture = rBody->CreateFixture(&bFixtureDef);

    sf::Texture *texture = &Global::txtManager.textures.at(_textureKeyID);
    rSprite.setTexture(*texture);
    rSprite.setOrigin(_size.x / 2, _size.y / 2);
    rSprite.setTextureRect(sf::IntRect(_textRect.left, _textRect.top, _textRect.width, _textRect.height));
    rSprite.setPosition(_position.x, _position.y);
    created = true;
}

Upvotes: 0

Views: 203

Answers (1)

Louis Langholtz
Louis Langholtz

Reputation: 3123

In your code to delete the body I don't see any check of whether the body has already been destroyed. Having such a check will prevent memory issues; potentially like the crashing you described.

Upvotes: 1

Related Questions