Page 1 of 1

Problem with world.DestroyJoint()

Posted: Mon Mar 13, 2017 7:57 pm
by evanbarmes
I create my joint from Truck.cpp like this and everything works perfectly and responds as intended.

Code: Select all

hitch = new b2RevoluteJointDef();
    hitch->Initialize(trailer, body, trailer->GetWorldCenter()+b2Vec2(0, 3));
    hitch->collideConnected = false;
   
    _world->CreateJoint(hitch);


Then, also from Truck.cpp, I give "layer" which handles the world step and all that, a reference to the joint I want to destroy...

Code: Select all

if (keyCode == cocos2d::EventKeyboard::KeyCode::KEY_SPACE) {

        if (hitch != NULL) {
            layer->toDestroy = (b2Joint*)hitch;
        }
       
    }


Then, after "layer" updates the world, I try to destroy the joint...

Code: Select all

void Main::update(float delta) {

    _world->Step(delta, 10, 10);
   
    if(toDestroy != NULL) {
        _world->DestroyJoint(toDestroy);
        toDestroy = NULL;
       
    }


but I get an EXC_BAD_ACCESS error inside

Code: Select all

void b2World::DestroyJoint(b2Joint* j)


at this point...

Code: Select all

// Remove from body 1.
   if (j->m_edgeA.prev)
   {
      j->m_edgeA.prev->next = j->m_edgeA.next;
   }


with the debugger revealing that both j->m_edgeA.prev->next and j->m_edgeA.next are NULL.


I would be super grateful for any help anyone can offer. Is this something I'm doing wrong, or possibly a bug in the Box2D code???

Re: Problem with world.DestroyJoint()

Posted: Tue Jun 27, 2017 5:54 pm
by CrowbarBarian
It's a simple error with the code. You're trying to destroy the reference to a b2RevoluteJointDef, not a b2RevoluteJoint. Add a variable somewhere in your truck class called something like "b2RevoluteJoint* hitch_joint". Then change the line

Code: Select all

_world->CreateJoint(hitch);
to

Code: Select all

hitch_joint = _world->CreateJoint(hitch);

This saves the correct reference to the joint object.
Then, change

Code: Select all

        if (hitch != NULL) {
            layer->toDestroy = (b2Joint*)hitch;
        }

to

Code: Select all

        if (hitch_joint != NULL) {
            layer->toDestroy = (b2Joint*)hitch_joint;
        }


That should solve the problem.