1
votes

I recently started to work with box2d, and currently I am having a problem with drawing box2d. Right now, my boxes are drawn with only boundary lines. But I want to draw Textures at where the box exists.

Though, I am not sure if the right way is to assign texture to box2d, or draw texture using Sprite over the box.

Is there a way to assign texture to box2d? or another way to render textures when using box2d?

2
typically physics and graphics are done separately, and the graphics will draw it's own sprite given the position and angle of the physics object (or by it's model matrix if it's in 3d). - Robert Rouhani

2 Answers

0
votes

There are basically two approaches to this that I've used.

  1. In a GameManager/GameWorld class implement a update/tick method that gets called every frame. After calling world->Step(delta, 10, 10); loop through all the bodies in the world and update their Sprites position. Note that when you create the bodies many will use the body.userData member to store a pointer to the Sprite "attached" to this body.

    for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) 
    {
      if (b->GetUserData() != NULL) {
        CCSprite *spriteData = (CCSprite *)b->GetUserData();
        spriteData.position = ccp(b->GetPosition().x * PTM_RATIO,b->GetPosition().y * PTM_RATIO);
        spriteData.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
      }
    }
    
  2. Say that you have an object that has a class called player. You can implement a tick/update method in this class that updates it's own sprite with the position of the body... like:

    [self setPosition:ccp(body->GetPosition().x * PTM_RATIO, body->GetPosition().y * PTM_RATIO)];
    

You'll need to have a pointer to the b2_body and add this instance to the CCLayer where the main update/tick/step is implemented.

0
votes

You have to find actual body position for example, in render method you implement following things to find body position and attach texture to it.

ballPosition = ballBody.getPosition();

and apply position to texture drawn on screen