bbm20891
bbm20891

Reputation: 144

How to add sprite in box2d body (c++, cocos2d)?

setTouchEnabled(true);

    ball=CCSprite::create("soccer_ball.png");
    ball->setPosition(ccp(100,100));
    addChild(ball,1);

    //CREATE WORLD
     b2Vec2 gravity(0, -9.8); //normal earth gravity, 9.8 m/s/s straight down!
    bool doSleep = true;
    myWorld = new b2World(gravity);
    myWorld->SetAllowSleeping(doSleep);

    //BODY DEFINITION
   myBodyDef.type = b2_dynamicBody; //this will be a dynamic body
   myBodyDef.position.Set(0, 20); //set the starting position
   myBodyDef.angle = 0; //set the starting angle    return true;
   myBodyDef.userData=ball;

   //CREATE SHAPE
   b2CircleShape ballShape;
   ballShape.m_p.Set(2.0f,3.0f);
   ballShape.m_radius=50.0/PTM_RATIO;

   //CREATE BODY

    dynamicBody = myWorld->CreateBody(&myBodyDef);

 //FIXTURE DEFINITION

  b2FixtureDef ballFixtureDef;
  ballFixtureDef.shape = &ballShape;
  ballFixtureDef.density = 1;
  dynamicBody->CreateFixture(&ballFixtureDef);

}

void HelloWorld::update()
{
float32 timeStep = 1/20.0;      //the length of time passed to simulate (seconds)
  int32 velocityIterations = 8;   //how strongly to correct velocity
  int32 positionIterations = 3;   //how strongly to correct position

  myWorld->Step( timeStep, velocityIterations, positionIterations);
}

I am learning box2d basic concepts and i have put my code here. I created a box2d circle shape. now i want to add sprite of ball in that circle shape. I have used myBodyDef.userData=ball; but it is not working .. i used gles-render code to debug draw but in that circle body is different and ball sprite is different. when i applyforce or impluse body works perfectly but dont attached to ball sprite..is any mistake in my code. I want to apply force to ball and ball should bounce according to physics but i can not attach to body plz help me.

Body and sprite looks like this enter image description here

Upvotes: 0

Views: 1293

Answers (1)

Bilal Ahmed
Bilal Ahmed

Reputation: 358

Here's my version working for V-3.6:

void GamePlayScreen::update(float dt) {

phyWorld->Step(dt, 8, 1);

// Iterate over the bodies in the physics phyWorld
for (b2Body* b = phyWorld->GetBodyList(); b; b = b->GetNext()) {
    if (b->GetUserData() != NULL) {
        // Synchronize the AtlasSprites position and rotation with the corresponding body
        Sprite* sprActor = (Sprite*) b->GetUserData();

        sprActor->setPosition(b->GetPosition().x * PTM_RATIO,
                b->GetPosition().y * PTM_RATIO);

        sprActor->setRotation(-1 * CC_RADIANS_TO_DEGREES(b->GetAngle()));

    }
}

}

Upvotes: 0

Related Questions