4
votes

I would like to Copy a body (including fixtures, joints attached to it) in my box2d world.

I have tried nothing because I don't see any methods that can do that.

So my question is : is there possible to copy a body ? if yes, how to do this.

2

2 Answers

3
votes

My advise is to create method that will be creating groups of bodies and just to apply velocity etc of base group to them.

    Body createGroup()
    {
        //creating bodies, joints etc
        //returning the root body for joint group
    }

If you want to copy bodies one by one there is no simple method to achieve it unfortunately. Although I think that it is possible to implement it.

To create a body copy you generally need:

  • BodyDef and FixtureDef object - it is not possible to get bodyDef from the body, but you can easile write it to the UserData object when creating body and then just get the UserData

    BodyDef bodyDef = new BodyDef();
    FixtureDef fixtureDef = new FixtureDef();
    
    //setting up body and fixture definitions
    
    body = world.createBody(bodyDef);
    
    body.createFixture(fixtureDef).setUserData( fixtureDef );
    body.setUserData( bodyDef );
    
    ...
    
    //then just somewhere in your app
    BodyDef copyBodyDef = (BodyDef) body.getUserData();
    FixtureDef copyFixtureDef = (FixtureDef) body.getFixtureList().first().getUserData();
    

    you should also handle a situation when you have more than one fixture attached to body by iterating over fixture list

  • Position, Velocity, Damping and others - you can set body some characteristics during app life and you can also retrieve them by using functions like

    Vector2 getLinearVelocity();
    Vector2 getPosition()
    ...
    

    you can read about bodies in official box2d manual although in my opinion the better reference is the LibGDX one.

  • Joints - and this is in my opinion the biggest problem. You can iterate over the joints using:

    for(JointEdge edge : body.getJointList())
    {
        Joint joint = edge.joint; //joint has getUserData() so you can again remember joint definition
        Body jointBody = edge.other;
    }
    

    but it doesn't seems to be easy to copy exactly the same configuration since you would have to check which joints copies you have already created (if you iterate over body joints you should also iterate over their neibghbour ones and so on...)

0
votes

You can use the Utils library from Dermetfan, as proposed in this post (LibGDX forum). It contains some very handy box2dUtils. Something like Body clonedBody = clone(body,true); should meet your needs.