Instantiating bodies from a prototype in a RUBE document

General discussion about the R.U.B.E editor
Eddy8555
Posts: 42
Joined: Sat Apr 27, 2013 3:01 pm

Re: Instantiating bodies from a prototype in a RUBE document

Post by Eddy8555 »

Ugh... obviously it's read and written to different b2dJson objects. My barely born C++ is failing me...
iforce2d
Site Admin
Posts: 861
Joined: Sat Dec 22, 2012 7:20 pm

Re: Instantiating bodies from a prototype in a RUBE document

Post by iforce2d »

Notice that writeToFile has just two parameters, the Box2D world and the file to write to, and a Box2D world knows nothing about images. To save information about images, you need to give the b2dJson that information before saving. Here is a rough outline of how you would do that:

Code: Select all

        b2dJson json;

        b2dJsonImage* img = new b2dJsonImage();
        img->m_body = ...;
        img->m_name = ...;
        img->m_file = ...;
        img->m_center = ...;
        img->m_angle = ...;
        img->m_scale = ...;
        img->m_aspectScale = ...;
        img->m_flip = ...;
        img->m_filter = ...;
        img->m_opacity = ...;
        img->m_renderOrder = ...;
        img->m_colorTint[0] = ...;
        img->m_colorTint[1] = ...;
        img->m_colorTint[2] = ...;
        img->m_colorTint[3] = ...;
        float aspect = imageWidthPixels / (float)imageHeightPixels;
        img->updateCorners( aspect );
        img->updateUVs( aspect );
        json.addImage(img);

        json.writeToFile( world, filename );
Perhaps not all of these will be necessary, but it would be good practice to set them anyway. If this seems like a pain in the ass, remember that's why we have an editor... b2dJson was originally intended to take a snapshot of only physics state, before RUBE's image-attaching feature even existed.
Eddy8555
Posts: 42
Joined: Sat Apr 27, 2013 3:01 pm

Re: Instantiating bodies from a prototype in a RUBE document

Post by Eddy8555 »

Yes, I know the editor is more elegant but I am trying to do something the editor doesn't -- load new objects of my game based on named objects from the json.

The good news is I finally got it to work :o

I made the json a class object, so it's only instantiated once, upon the first load, and then modified the afterLoadProcessing to work for one body. Then I call the following function whenever I want to add a body to my layer:

Code: Select all

-(void) loadBody:(NSString*) bodyName {
    b2Body *b = json.getBodyByName([bodyName UTF8String]); 
    Json::Value bodyValue = json.b2j(b);
    b2Body *body = json.j2b2Body(m_world, bodyValue);

    [self afterLoadBodyProcessing:body]; // modified from afterLoadProcessing to work for only one body
Thanks for all your help, iforce.
Post Reply