void MainGameLayer::addBox(Point p) { // Define the dynamic body. //Set up a 1m squared box in the physics world b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO); b2Body *body = (Box2dDirectorLayer::world)->CreateBody(&bodyDef); // Define another box shape for our dynamic body. b2PolygonShape dynamicBox; //dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box dynamicBox.SetAsBox(.5f, .8f);//These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); // body to sprite Texture2D *texture = TextureCache::getInstance()->addImage("gabriel.png"); PhysicsSprite *sprite = PhysicsSprite::createWithTexture(texture); addChild(sprite); sprite->setB2Body(body); sprite->setPTMRatio(PTM_RATIO); sprite->setPosition( Point( p.x, p.y) ); }
void LiquidScene::drawBox2dSpriteAt(LiquidScene::Box2dSpriteData data, Point pos) { if (data.file == NULL) { return; } b2Body* body; b2BodyDef bodyDef; b2CircleShape shape; b2FixtureDef fixtureDef; PhysicsSprite* physicsSprite = PhysicsSprite::create(data.file); float scale = Director::getInstance()->getContentScaleFactor(); physicsSprite->cocos2d::Node::setScale(scale); bodyDef.type = b2_dynamicBody; bodyDef.position.Set((pos.x) / PT_RATIO, (pos.y) / PT_RATIO); bodyDef.userData = physicsSprite; body = world->CreateBody(&bodyDef); shape.m_radius = physicsSprite->getContentSize().width / PT_RATIO; fixtureDef.shape = &shape; fixtureDef.density = data.density; fixtureDef.friction = data.friction; body->CreateFixture(&fixtureDef); this->addChild(physicsSprite); physicsSprite->setB2Body(body); physicsSprite->setPTMRatio(PT_RATIO); physicsSprite->setPosition(pos); }
void Box2DTestLayer::addNewSpriteAtPosition(Point p) { CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); // Define the dynamic body. //Set up a 1m squared box in the physics world b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO); b2Body *body = world->CreateBody(&bodyDef); // Define another box shape for our dynamic body. b2PolygonShape dynamicBox; dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); #if CC_ENABLE_BOX2D_INTEGRATION Node *parent = this->getChildByTag(kTagParentNode); //We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is //just randomly picking one of the images int idx = (CCRANDOM_0_1() > .5 ? 0:1); int idy = (CCRANDOM_0_1() > .5 ? 0:1); PhysicsSprite *sprite = PhysicsSprite::createWithTexture(_spriteTexture,Rect(32 * idx,32 * idy,32,32)); parent->addChild(sprite); sprite->setB2Body(body); sprite->setPTMRatio(PTM_RATIO); sprite->setPosition( Point( p.x, p.y) ); #endif }