Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

box2d CreateFixture with b2FixtureDef gives pure virtual function call

i have this code that gives me run time error in the line :

  body->CreateFixture(&boxDef) 

im using cocos2d-x 2.1.5 with box2d 2.2.1 in windows

CCSprite *sprite = CCSprite::create(imageName.c_str());
    this->addChild(sprite,1);

    b2BodyDef bodyDef;
    bodyDef.type = isStatic?b2_staticBody:b2_dynamicBody;
    bodyDef.position.Set((position.x+sprite->getContentSize().width/2.0f)/PTM_RATIO,
                         (position.y+sprite->getContentSize().height/2.0f)/PTM_RATIO);
    bodyDef.angle = CC_DEGREES_TO_RADIANS(rotation);
    bodyDef.userData = sprite;
    b2Body *body = world->CreateBody(&bodyDef);

    b2FixtureDef boxDef;
    if (isCircle)
    {
        b2CircleShape circle;
        circle.m_radius = sprite->getContentSize().width/2.0f/PTM_RATIO;
        boxDef.shape = &circle;
    }
    else
    {
        b2PolygonShape box;
        box.SetAsBox(sprite->getContentSize().width/2.0f/PTM_RATIO, sprite->getContentSize().height/2.0f/PTM_RATIO);
        boxDef.shape = &box;
    }

    if (isEnemy)
    {
        boxDef.userData = (void*)1;
        enemies->insert(body);

    }

    boxDef.density = 0.5f;
    body->CreateFixture(&boxDef)  //<-- HERE IS THE RUN TIME ERROR 

;

when i debug the box2d code im getting to b2Fixture.cpp in the method :

void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def)

in the line :

m_shape = def->shape->Clone(allocator);

getting the runtime error :

R6025 pure virtual function call

like image 232
user63898 Avatar asked Jan 12 '23 03:01

user63898


1 Answers

Tricky one. I ran into this myself a couple times. It has to do with variable scope.

The boxDef.shape is the problem. You create the shapes as local variables in the if/else blocks and then assign them to boxDef. As soon as execution leaves the if/else block scope those local variables will be garbage. The boxDef.shape now points to freed memory.

The solution is to keep the shape variables in scope by moving the circle and box shape declarations before the if/else block.

like image 110
LearnCocos2D Avatar answered Jan 20 '23 17:01

LearnCocos2D