简单实例(世界创建,边界创建,绑定精灵)

世界创建


b2Vec2 gravity(0.0f,-10.0f); 
    world=new b2World(gravity);
    world->SetAllowSleeping(true);
    world->SetContinuousPhysics(true);


边界创建


//world box
    b2BodyDef groundBodyDef;
    groundBodyDef.position.SetZero();
    //create body
    b2Body *groundBody=world->CreateBody(&groundBodyDef);
    //create Edges
    b2EdgeShape groundBox;;
    groundBox.Set(b2Vec2(0,0),b2Vec2(winSize.width/PTM_RATIO,0));
    groundBody->CreateFixture(&groundBox,0);
    groundBox.Set(b2Vec2(0,0),b2Vec2(0,winSize.height/PTM_RATIO));
    groundBody->CreateFixture(&groundBox,0);
    groundBox.Set(b2Vec2(0,winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO,winSize.height/PTM_RATIO));
    groundBody->CreateFixture(&groundBox,0);
    groundBox.Set(b2Vec2(winSize.width/PTM_RATIO,winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO,0));
    groundBody->CreateFixture(&groundBox,0);


精灵创建


//create sprite
    batch=CCSpriteBatchNode::create("CloseNormal.png",100);
    this->addChild(batch);
    m_pSpriteTexture=batch->getTexture();
    setTouchEnabled(true);
    addNewSpriteAtPosition(ccp(100,100));
    scheduleUpdate();
void HelloWorld::addNewSpriteAtPosition(CCPoint point)
{
  CCSprite *sprite=CCSprite::create(m_pSpriteTexture,CCRectMake(0,0,m_pSpriteTexture->getContentSize().width,m_pSpriteTexture->getContentSize().height));
  batch->addChild(sprite);
  sprite->setPosition(point);
  sprite->autorelease();
  //CCLOG("a");
  b2BodyDef bodyDef;
  bodyDef.type=b2_dynamicBody;
  bodyDef.position.Set(point.x/PTM_RATIO,point.y/PTM_RATIO);
  bodyDef.userData=sprite;
  b2Body *body=world->CreateBody(&bodyDef);
  
  b2PolygonShape shapeBox;
  shapeBox.SetAsBox(.5f,.5f);


  b2FixtureDef fixtureDef;
  fixtureDef.shape=&shapeBox;
  fixtureDef.density=1.0f;
  fixtureDef.friction=0.3f;


  body->CreateFixture(&fixtureDef);
  
}


绑定精灵


void HelloWorld::update(float dt)
{
  world->Step(dt,8,1);
  //CCLOG("%d",world->GetBodyCount());
  for(b2Body *b=world->GetBodyList();b;b=b->GetNext())
  {
    if(b->GetUserData()!=NULL)
    {
      //CCLOG("ab");
      CCSprite *sprite=(CCSprite*)b->GetUserData();
      
      sprite->setPosition(ccp(b->GetPosition().x*PTM_RATIO,b->GetPosition().y*PTM_RATIO));
      sprite->setRotation((-1)*CC_RADIANS_TO_DEGREES(b->GetAngle()));
      //CCLOG("%f,%f",sprite->getPositionX(),sprite->getPositionY());
      
    }
  }}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值