void createWorld (b2World& world) { m_stepCount = 0; m_angularVelocity = 0; { b2BodyDef bd; bd.position.Set(0, 0); b2Body * body = world.CreateBody(&bd); b2PolygonShape * shape = new b2PolygonShape(); shape->SetAsEdge(b2Vec2(-10, 0), b2Vec2(10, 0)); body->CreateFixture(shape, 0); shape->SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0); body->CreateFixture(shape, 0); delete shape; } { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(0, 20); b2PolygonShape * shape = new b2PolygonShape(); shape->SetAsBox(2, 0.1f); m_body = world.CreateBody(&bd); m_body->CreateFixture(shape, 1); m_angularVelocity = 33.468121f; m_body->SetLinearVelocity(b2Vec2(0, -100)); m_body->SetAngularVelocity(m_angularVelocity); delete shape; } }
void createWorld (b2World& world) { { b2BodyDef bd; b2Body * ground = world.CreateBody(&bd); b2EdgeShape* shape = new b2EdgeShape(); shape->Set(b2Vec2(-40, 0), b2Vec2(40, 0)); ground->CreateFixture(shape, 0.0f); delete shape; } { b2CircleShape * shape = new b2CircleShape(); shape->m_radius = 1; b2FixtureDef fd; fd.shape = shape; fd.density = 1.0f; const int length = 7; float restitution[length] = {0, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f}; for (int i = 0; i < length; i++) { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(-10.0f + 3.0f * i, 20.0f); b2Body * body = world.CreateBody(&bd); fd.restitution = restitution[i]; body->CreateFixture(&fd); } delete shape; } }
void ReleaseNormalKeyInput (unsigned char key, int x, int y) { printf (" input %d\n", key ); switch (key) { case 'w': break; case 'f': break; case 'a': break; case 'r': for ( b2Body * b = myWorld.GetBodyList (); b; b = b->GetNext () ) { myWorld.DestroyBody (b); } delete agent; agent = new Agent (myWorld); readFile ("map.txt"); break; case '1': break; default: break; } }
void createWorld (b2World& world) { { b2BodyDef bd; b2Body * ground = world.CreateBody(&bd); b2EdgeShape* shape = new b2EdgeShape(); shape->Set(b2Vec2(-40, 0), b2Vec2(40, 0)); ground->CreateFixture(shape, 0); delete shape; } { b2CircleShape * shape = new b2CircleShape(); shape->m_radius = 1.0f; for (int i = 0; i < e_count; i++) { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(0, 4.0f + 3.0f * i); b2Body * body = world.CreateBody(&bd); body->CreateFixture(shape, 1.0f); } delete shape; } }
void ConfinementTests::SetUp() { // Define the gravity vector. b2Vec2 gravity(0.0f, -10.0f); // Construct a world object, which will hold and simulate the rigid bodies. m_world = new b2World(gravity); // Create the ground body const b2BodyDef groundBodyDef; m_groundBody = m_world->CreateBody(&groundBodyDef); // Create the particle system b2ParticleSystemDef particleSystemDef; particleSystemDef.radius = 0.01f; m_particleSystem = m_world->CreateParticleSystem(&particleSystemDef); // Create particles b2ParticleGroupDef particleDef; b2PolygonShape particleShape; particleShape.SetAsBox(WIDTH, HEIGHT); particleDef.shape = &particleShape; m_particleGroup = m_particleSystem->CreateParticleGroup(particleDef); }
void addStaticShapes(b2World& world) { ShapeFactory factory { constants::RENDER_SCALE }; // Add the nondestructible screen edges std::vector<b2Vec2> boundaryPoints = { b2Vec2{ 0.0f, 0.0f }, b2Vec2{ 0.0f, screenHeight }, b2Vec2{ screenWidth, screenHeight }, b2Vec2{ screenWidth, 0.0f } }; auto boundaryShape = factory.chain(boundaryPoints.data(), boundaryPoints.size()); b2BodyDef boundaryDef; b2Body* boundaryBody = world.CreateBody(&boundaryDef); auto boundaryFixture = boundaryBody->CreateFixture(boundaryShape.get(), 0.0f); auto filter = boundaryFixture->GetFilterData(); filter.categoryBits = Shape::normal; boundaryFixture->SetFilterData(filter); // Add a destructible polygon std::vector<b2Vec2> polygonPoints = { b2Vec2{ screenWidth * 0.1f, screenHeight * 0.4f }, b2Vec2{ screenWidth * 0.1f, screenHeight * 0.95f }, b2Vec2{ screenWidth * 0.9f, screenHeight * 0.95f }, b2Vec2{ screenWidth * 0.9f, screenHeight * 0.7f }, b2Vec2{ screenWidth * 0.4f, screenHeight * 0.4f } }; auto polygonShape = factory.chain(polygonPoints.data(), polygonPoints.size()); b2BodyDef polygonDef; b2Body* polygonBody = world.CreateBody(&polygonDef); auto polygonFixture = polygonBody->CreateFixture(polygonShape.get(), 0.0f); filter.categoryBits = Shape::destructible; polygonFixture->SetFilterData(filter); }
void step(b2World& world, float dt) { const int maxSteps = 20; const float fixedDt = 1.0f / 60.f; const float minDt = fixedDt / 10.f; int stepsPerformed = 0; float frameTime = dt; while (frameTime > 0.0f && stepsPerformed < maxSteps) { float delta = (std::min)(frameTime, fixedDt); frameTime -= delta; if (frameTime < minDt) { delta += frameTime; frameTime = 0.0f; } const int velocityIterations = 8; const int positionIterations = 3; world.Step(delta, velocityIterations, positionIterations); } world.ClearForces(); }
// Destroy all particles in the system, drop a particle onto the fixture and // keep track of the number of contacts with the fixture in addition to the // stuck particle candiates. void BodyContactTests::DropParticle() { // Reset counters. m_contacts = 0; m_stuck = 0; DestroyAllParticles(); const float32 timeStep = 1.0f / 60.0f; const int32 timeout = (int32)(1.0f / timeStep) * 10; // 10 "seconds" const int32 velocityIterations = 6; const int32 positionIterations = 2; // Step once to eliminate particles. m_world->Step(timeStep, velocityIterations, positionIterations); b2ParticleDef pd; pd.position.Set(0.0f, 33.0f); pd.velocity.Set(0.0f, -1.0f); m_particleSystem->CreateParticle(pd); for (int32 i = 0; i < timeout; ++i) { m_world->Step(timeStep, velocityIterations, positionIterations); m_contacts += m_particleSystem->GetBodyContactCount(); int32 stuck = m_particleSystem->GetStuckCandidateCount(); if (stuck) { m_stuck += stuck; // Should always be particle 0. EXPECT_EQ(*(m_particleSystem->GetStuckCandidates()), 0); } } }
void processRemoval(b2Vec2 removalPosition, float removalRadius, b2World& world, bool simplifyGeometry) { auto foundBodies = queryDestructibleBodies(removalPosition, removalRadius, world); auto batch = matchBodiesToRings(foundBodies.begin(), foundBodies.end()); // Partition the shapes by area, so that elements to be processed are at the beginning auto borderIt = std::partition(batch.begin(), batch.end(), [](const match_t& m) { const double areaEpsilon = 0.02; return bg::area(m.second) > areaEpsilon; }); // Remove small shapes std::for_each(borderIt, batch.end(), [&](const match_t& m) { world.DestroyBody(m.first); }); // Subtract the input polygon from each shape returned from the query ring_t diff = makeConvexRing(removalPosition, removalRadius, 16); boost::geometry::correct(diff); typedef std::pair<std::unique_ptr<b2ChainShape>, b2Filter> shape_property_t; std::vector<shape_property_t> resultShapes; std::for_each(batch.begin(), borderIt, [&](const match_t& m) { auto subtractionResult = subtract(m.second, diff); // Simplify the results if (simplifyGeometry) { simplify(subtractionResult); } // Convert the rings to b2ChainShapes and add to result shapes auto converted = convertGeometry(subtractionResult); auto moveBegin = std::make_move_iterator(converted.begin()); auto moveEnd = std::make_move_iterator(converted.end()); std::transform(moveBegin, moveEnd, std::back_inserter(resultShapes), [&](std::unique_ptr<b2ChainShape> converted) { auto filter = m.first->GetFixtureList()->GetFilterData(); return std::make_pair(std::move(converted), filter); }); if (!subtractionResult.empty()) { world.DestroyBody(m.first); } }); for (auto&& s : resultShapes) { b2BodyDef bd; b2Body* body = world.CreateBody(&bd); auto fixture = body->CreateFixture(s.first.get(), 0.0f); fixture->SetFilterData(s.second); } }
void createEntity(tmx::MapObject mapObject, b2World& box2dWorld, anax::World& anaxWorld) { b2Vec2 statingPosition = tmx::SfToBoxVec(mapObject.GetPosition()); b2Vec2 endPosition = tmx::SfToBoxVec(sf::Vector2f(mapObject.GetPosition().x + mapObject.GetAABB().width, mapObject.GetPosition().y)); b2Body* firstBodyToJoinWith = createStartingBody(statingPosition, box2dWorld); b2Body* prevBody = firstBodyToJoinWith; { b2PolygonShape shape; shape.SetAsBox(0.5f, 0.125f); b2FixtureDef fd = getRopeFixture(shape); b2RevoluteJointDef jd; jd.collideConnected = false; const int32 N = ceilf((mapObject.GetAABB().width / 30) / (1.0f )) + 1; for (int32 xVal = 1; xVal < N; ++xVal) { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(statingPosition.x + xVal , statingPosition.y ); if (xVal == N - 1) { bd.type = b2_staticBody; shape.SetAsBox(0.1f, 0.1f); fd.density = 1.0f; bd.position.Set(endPosition.x, endPosition.y); } b2Body* body = box2dWorld.CreateBody(&bd); body->CreateFixture(&fd); auto objectEntity = anaxWorld.createEntity(); auto& texCoordsComp = objectEntity.addComponent<Texcoords>(); auto& physComp = objectEntity.addComponent<PhysicsComponent>(); auto& splitDirectionComp = objectEntity.addComponent<SplitDirectionComponent>(); auto& breakableJointComp = objectEntity.addComponent<BreakableJointComponent>(); breakableJointComp.maxWeight = 1 ; b2Vec2 anchor( statingPosition.x + xVal , statingPosition.y ); jd.Initialize(prevBody, body, anchor); box2dWorld.CreateJoint(&jd); physComp.physicsBody = body; objectEntity.activate(); prevBody = body; } } }
void Box2DDebugRenderer::renderBodies ( b2World& world) { renderer.begin(ShapeRenderer::ShapeType::Line); if (mDrawBodies || mDrawAABBs) { for (b2Body * body = world.GetBodyList(); body; body = body->GetNext()) { const b2Transform& transform = body->GetTransform(); for (b2Fixture* fixture = body->GetFixtureList(); fixture; fixture = fixture->GetNext()) { if (mDrawBodies) { if (body->IsActive() == false) drawShape(*fixture, transform, SHAPE_NOT_ACTIVE); else if (body->GetType() == b2_staticBody) drawShape(*fixture, transform, SHAPE_STATIC); else if (body->GetType() == b2_kinematicBody) drawShape(*fixture, transform, SHAPE_KINEMATIC); else if (body->IsAwake() == false) drawShape(*fixture, transform, SHAPE_NOT_AWAKE); else drawShape(*fixture, transform, SHAPE_AWAKE); } if (mDrawAABBs) { drawAABB(*fixture, transform); } } } } if (mDrawJoints) { for (b2Joint* joint = world.GetJointList(); joint; joint= joint->GetNext()) { drawJoint(*joint); } } renderer.end(); if (gl10 != NULL) { gl10->glPointSize(3); } renderer.begin(ShapeRenderer::ShapeType::Point); for (b2Contact* contact = world.GetContactList(); contact; contact = contact->GetNext()) { drawContact(*contact); } renderer.end(); if (gl10 != NULL) { gl10->glPointSize(1); } }
GravityChanger::GravityChanger(b2World& world, float x, float y, bool flipped) : GameObject(world, x, y, "GravityChanger", new GravityChangerDrawable(x,y)), flipped(flipped) { b2BodyDef bodyDef; bodyDef.position.Set(x,y); b2Body* body_ptr=world.CreateBody(&bodyDef); b2PolygonShape shape1; shape1.SetAsBox(1.0f, 0.5f); check1=body_ptr->CreateFixture(&shape1,0.0f); b2PolygonShape shape2; shape2.SetAsBox(0.4f, 1.0f, b2Vec2(-1,-0.5f), 0); b2PolygonShape shape3; shape3.SetAsBox(0.4f, 1.0f, b2Vec2(1,-0.5f), 0); body_ptr->CreateFixture(&shape2,0); body_ptr->CreateFixture(&shape3,0); bodies.push_back(PhysBody(body_ptr, body_ptr->GetPosition(), body_ptr->GetAngle())); b2BodyDef bodyDef2; bodyDef2.position.Set(x,y-1.5f); bodyDef2.type = b2_dynamicBody; b2Body* button_ptr=world.CreateBody(&bodyDef2); button_ptr->SetGravityScale(0); b2PolygonShape buttonshape; buttonshape.SetAsBox(0.5f,0.5f); check2=button_ptr->CreateFixture(&buttonshape, 0); button_ptr->SetUserData(this); bodies.push_back(PhysBody(button_ptr, button_ptr->GetPosition(), button_ptr->GetAngle())); b2PrismaticJointDef prismDef; prismDef.bodyA = body_ptr; prismDef.localAnchorA = b2Vec2(0,-1); prismDef.bodyB = button_ptr; prismDef.localAnchorB = b2Vec2(0,0); prismDef.localAxisA = b2Vec2(0,1); prismDef.upperTranslation =1; prismDef.lowerTranslation =-0.5f; prismDef.enableLimit=true; prismDef.collideConnected=true; prismDef.enableMotor = true; prismDef.maxMotorForce=25; prismDef.motorSpeed=-3; world.CreateJoint(&prismDef); if (flipped) { bodies[0].body_ptr->SetTransform(bodies[0].original_pos-b2Vec2(0,1.5f), 3.14159); bodies[0].original_pos=bodies[0].body_ptr->GetTransform().p; bodies[0].original_rot=3.14159; bodies[1].body_ptr->SetTransform(bodies[1].original_pos+b2Vec2(0,1.5f), bodies[1].original_rot); bodies[1].original_pos=bodies[1].body_ptr->GetTransform().p; } }
void Box2DRenderer::render (Graphics& g, b2World& world, float left, float top, float right, float bottom, const Rectangle<float>& target) { graphics = &g; g.addTransform (AffineTransform::fromTargetPoints (left, top, target.getX(), target.getY(), right, top, target.getRight(), target.getY(), left, bottom, target.getX(), target.getBottom())); world.SetDebugDraw (this); world.DrawDebugData(); }
void FlipperRight::create(b2World& World, int MouseX, int MouseY) { //FLIPPER vertices[0].Set(0, -0.1); vertices[1].Set(-2, 0); vertices[2].Set(-2, 0.25); vertices[3].Set(0, 0.35); BodyDef.position = b2Vec2(MouseX/SCALE, MouseY/SCALE); BodyDef.type = b2_dynamicBody; Body = World.CreateBody(&BodyDef); Shape.Set(vertices, 4); FixtureDef.shape = &Shape; FixtureDef.density = 1.f; Body->CreateFixture(&FixtureDef); polygon.setPointCount(4); polygon.setPoint(0, sf::Vector2f( 0*SCALE, -0.1*SCALE)); polygon.setPoint(1, sf::Vector2f( -2*SCALE, 0*SCALE)); polygon.setPoint(2, sf::Vector2f( -2*SCALE, 0.25*SCALE)); polygon.setPoint(3, sf::Vector2f( 0*SCALE, 0.35*SCALE)); polygon.setFillColor(sf::Color(0,206,209)); //WALL BodyDef2.position = b2Vec2((MouseX+42)/SCALE, (MouseY-15)/SCALE); BodyDef2.type = b2_staticBody; Body2 = World.CreateBody(&BodyDef2); Shape2.SetAsBox((90/2)/SCALE, (10/2)/SCALE); FixtureDef2.density = 1.f; FixtureDef2.shape = &Shape2; Body2->CreateFixture(&FixtureDef2); Body2->SetTransform(Body2->GetPosition(), -0.4); rect.setSize(sf::Vector2f(90, 10)); rect.setOrigin(90/2, 10/2); rect.setFillColor(sf::Color(0,206,209)); //JOIN jointDef.Initialize(Body, Body2, b2Vec2(MouseX/SCALE,MouseY/SCALE)); jointDef.lowerAngle = -0.12f * b2_pi; jointDef.upperAngle = 0.12f * b2_pi; jointDef.enableLimit = true; jointDef.maxMotorTorque = 150.0f; jointDef.motorSpeed = 2.f; jointDef.collideConnected = false; jointDef.enableMotor = true; joint = (b2RevoluteJoint*)World.CreateJoint(&jointDef); }
void RevoluteJoint::Create(b2World &world, const BasicShape &joinedBody1, const BasicShape &joinedBody2, const b2Vec2 &anchor1, const b2Vec2 &anchor2, const bool collideConnected, const float lowerAngle, const float upperAngle, const bool enableLimit, const float maxMotorTorque, const float motorSpeed, const bool enableMotor, const float referenceAngle) { b_ptrJoinedBody1 = const_cast<b2Body*>(joinedBody1.GetBody()); b_ptrJoinedBody2 = const_cast<b2Body*>(joinedBody2.GetBody()); //b2RevoluteJointDef revoluteJointDefinition; _revoluteJointDefinition.bodyA = b_ptrJoinedBody1; _revoluteJointDefinition.bodyB = b_ptrJoinedBody2; _revoluteJointDefinition.localAnchorA = anchor1; _revoluteJointDefinition.localAnchorB = anchor2; _revoluteJointDefinition.collideConnected = collideConnected; _revoluteJointDefinition.lowerAngle = lowerAngle; _revoluteJointDefinition.upperAngle = upperAngle; _revoluteJointDefinition.enableLimit = enableLimit; _revoluteJointDefinition.maxMotorTorque = maxMotorTorque; _revoluteJointDefinition.motorSpeed = motorSpeed; _revoluteJointDefinition.enableMotor = enableMotor; _revoluteJointDefinition.referenceAngle = referenceAngle; b_ptrJoint = world.CreateJoint(&_revoluteJointDefinition); }
FixtureShape::FixtureShape(b2World & world, b2Vec2 initialPos, b2Vec2 size, unsigned ySize, float PPM, sf::Color color) : Shape(world, initialPos, ySize, PPM) { mShape = std::unique_ptr<sf::RectangleShape>(new sf::RectangleShape(sf::Vector2f(size.x,size.y))); mShape->setFillColor(color); mShape->setOrigin(size.x/2.f, size.y/2.f); world.DestroyBody(mBody); mBodyDef.type = b2_staticBody; mBody = world.CreateBody(&mBodyDef); mBodyShape = std::unique_ptr<b2PolygonShape>(new b2PolygonShape()); static_cast<b2PolygonShape*>(mBodyShape.get())->SetAsBox(size.x/(2*mPPM), size.y/(2*mPPM)); setBodyFix(0.3f, 0.5f, 0.25f); update(); }
void display_world(b2World& world,sf::RenderWindow& render) { world.Step(1.0/60,int32(8),int32(3)); render.clear(); for (b2Body* body=world.GetBodyList(); body!=nullptr; body=body->GetNext()) { sf::Shape* shape = static_cast<sf::Shape*>(body->GetUserData()); shape->setPosition(converter::meters_to_pixels(body->GetPosition().x),converter::meters_to_pixels(body->GetPosition().y)); shape->setRotation(converter::rad_to_deg<double>(body->GetAngle())); render.draw(*shape); } render.display(); }
Object::Object(sf::Vector2f s, sf::Color c, b2World& w, sf::Vector2f p) { objectType t = player; m_type = t; n++; shape.setSize(s); shape.setOrigin(s.x/2, s.y/2); shape.setFillColor(c); bodyDef.type = b2_dynamicBody; if(p.x == 0) bodyDef.position.Set(toB2(300), -toB2(300.0f/30-n*5)); else bodyDef.position.Set(toB2(p.x), -toB2(p.y)); dynamicBody.SetAsBox(toB2(10.0f), toB2(10.0f)); fixtureDef.shape = &dynamicBody; fixtureDef.density = 0.3f; fixtureDef.friction = 0.5f; body = w.CreateBody(&bodyDef); body->CreateFixture(&fixtureDef); hitbox.setSize(shape.getSize()); hitbox.setOutlineColor(sf::Color::Red); hitbox.setPosition(shape.getPosition()); hitbox.setOutlineThickness(1); }
void Box2dApp::update() { for( int i = 0; i < 10; ++i ){ mWorld->Step( 1 / 30.0f, 10, 10 ); } for( list<box1*>::iterator boxIt = mBoxes.begin(); boxIt != mBoxes.end(); ) { if((*boxIt)->isDead()){ ps.push_back(new particleSystem(200,(*boxIt)->getPosition(), (*boxIt)->getAngle())); boxIt = mBoxes.erase(boxIt); }else { (*boxIt)->update(); ++boxIt; } } for( list<particleSystem*>::iterator psIt = ps.begin(); psIt != ps.end();) { if((*psIt)->isDead() == true){ psIt = ps.erase(psIt);} else{ (*psIt)->update(); ++psIt; } } }
void Circle::make(b2World& w) { // shape b2CircleShape circle; circle.m_radius = PIXELS_TO_METERS(radius); // body if(!body_type_set) { if(density == 0.0f) { body_def.type = b2_staticBody; } else { body_def.type = b2_dynamicBody; } } body = w.CreateBody(&body_def); // fixture fixture_def.shape = &circle; fixture_def.density = density; fixture_def.friction = friction; fixture_def.restitution = restitution; body->CreateFixture(&fixture_def); // body->CreateFixture(&circle, 10); }
void Ex58AdvancedCollisionsApp::update() { if ( Rand::randInt( 100 ) == 90 ) { squares.push_back( new Square( world, Vec2f( Rand::randFloat( getWindowWidth() ), -10.0f ), 0.0f, 10.0f ) ); } if ( Rand::randInt( 100 ) == 90 ) { circles.push_back( new Circle( world, Vec2f( Rand::randFloat( getWindowWidth() ), -10.0f ), 0.0f, 10.0f ) ); } if ( Rand::randInt( 100 ) == 90 ) { triangles.push_back( new Triugolnik( world, Vec2f( Rand::randFloat( getWindowWidth() ), -10.0f ), 0.0f, 10.0f ) ); } world->Step( timeStep, velocityIterations, positionIterations ); for ( auto& s : squares ) { s->update(); } for ( auto& t : triangles ) { t->update(); } for ( auto& c : circles ) { c->update(); } }
void box2d_basicApp::setup() { b2Vec2 gravity( 0.0f, 5.0f ); mWorld = new b2World( gravity ); b2BodyDef groundBodyDef; groundBodyDef.position.Set( 0.0f, getWindowHeight() ); b2Body* groundBody = mWorld->CreateBody(&groundBodyDef); // Define the ground box shape. b2PolygonShape groundBox; // The extents are the half-widths of the box. groundBox.SetAsBox( getWindowWidth(), 10.0f ); // Add the ground fixture to the ground body. groundBody->CreateFixture(&groundBox, 0.0f); //auto ctx = audio::Context::master(); //auto sourceFile = /*, ctx->getSampleRate()*/);//(app::loadResource("1.wav")); //audio::BufferRef buffer = sourceFile->loadBuffer(); // mBufferPlayerNode = ctx->makeNode( new audio::BufferPlayerNode( buffer ) ); // // add a Gain to reduce the volume // mGain = ctx->makeNode( new audio::GainNode( 0.5f ) ); // // connect and enable the Context // mBufferPlayerNode >> mGain >> ctx->getOutput(); // ctx->enable(); //float volume = 1.0f - (float)event.getPos().y / (float)getWindowHeight(); //float pan = (float)event.getPos().x / (float)getWindowWidth(); //mVoice->setVolume( volume ); //mVoice->setPan( pan ); new_game(); }
void Enemy::Initialize(b2World& world, b2Vec2 position) { bodyDef.position = position; bodyDef.type = b2_dynamicBody; bodyDef.fixedRotation = true; body = world.CreateBody(&bodyDef); Convert convert; b2Vec2 vs0, vs1, vs2, vs3; b2Vec2* vs = new b2Vec2[4]; vs0 = convert.CoordPixelsToWorld(0, 50, 50.0f, 50.0f); vs1 = convert.CoordPixelsToWorld(0, 0, 50.0f, 50.0f); vs2 = convert.CoordPixelsToWorld(50, 0, 50.0f, 50.0f); vs3 = convert.CoordPixelsToWorld(50, 50, 50.0f, 50.0f); vs[0].Set(vs0.x, vs0.y); vs[1].Set(vs1.x, vs1.y); vs[2].Set(vs2.x, vs2.y); vs[3].Set(vs3.x, vs3.y); shape.Set(vs, 4); delete vs; fixtureDef.density = 1.0f; fixtureDef.friction = 0.0f; fixtureDef.shape = &shape; body->CreateFixture(&fixtureDef); b2Fixture* enemySensorFixture = body->CreateFixture(&fixtureDef); ContactUserData* cud = new ContactUserData(); cud->type = ContactUserData::Type::ENEMY; cud->data = this; enemySensorFixture->SetUserData(cud); }
void Rectangle::make(b2World& w) { // shape b2PolygonShape shape; shape.SetAsBox(PIXELS_TO_METERS(hw),PIXELS_TO_METERS(hh)); // body if(!body_type_set) { if(density == 0.0f) { body_def.type = b2_staticBody; printf("Creating static rect.\n"); } else { body_def.type = b2_dynamicBody; } } body_def.position.Set(PIXELS_TO_METERS(x+hw), PIXELS_TO_METERS(y+hh)); body = w.CreateBody(&body_def); // fixture fixture_def.shape = &shape; fixture_def.density = density; fixture_def.friction = friction; fixture_def.restitution = restitution; body->CreateFixture(&shape, 0.0f); }
DynamicBox::DynamicBox(std::string name, float x, float y, float rotation, b2World& world) : Collidable(name) { std::ifstream file(name.c_str()); float density; float friction; std::string fileName; file >> fileName >> density >> friction; sprite.setTexture(rm->getTexture(fileName)); float width = sprite.getGlobalBounds().width; float height = sprite.getGlobalBounds().height; sprite.setPosition(x, y); sprite.setOrigin(width/2.f, height/2.f); DEF.position.Set((x+width/2.f)/PPM, (y+height/2.f)/PPM); DEF.type = b2_dynamicBody; DEF.angle = rotation; DEF.linearDamping = 0.5f; SHAPE.SetAsBox(width/2.f/PPM, height/2.f/PPM); body = world.CreateBody(&DEF); FIX.shape = &SHAPE; FIX.density = density; FIX.friction = friction; //FIX.linearDamping = .2; FIX.restitution = 0.0; body->CreateFixture(&FIX); body->SetUserData(this); }
bool maybeCreateJoint( b2World& world, Stroke* other ) { if ( (m_attributes&ATTRIB_CLASSBITS) != (other->m_attributes&ATTRIB_CLASSBITS) ) { return false; // can only joint matching classes } else if ( hasAttribute(ATTRIB_GROUND) ) { return true; // no point jointing grounds } else if ( m_body && other->body() ) { transform(); int n = m_xformedPath.numPoints(); for ( int end=0; end<2; end++ ) { if ( !m_jointed[end] ) { const Vec2& p = m_xformedPath.point( end ? n-1 : 0 ); if ( other->distanceTo( p ) <= JOINT_TOLERANCE ) { //printf("jointed end %d d=%f\n",end,other->distanceTo( p )); b2Vec2 pw = p; pw *= 1.0f/PIXELS_PER_METREf; JointDef j( m_body, other->m_body, pw ); world.CreateJoint( &j ); m_jointed[end] = true; } } } } if ( m_body ) { return m_jointed[0] && m_jointed[1]; } return true; ///nothing to do }
void createBodies( b2World& world ) { process(); if ( hasAttribute( ATTRIB_DECOR ) ){ return; //decorators have no physical embodiment } int n = m_shapePath.numPoints(); if ( n > 1 ) { b2BodyDef bodyDef; bodyDef.position = m_origin; bodyDef.position *= 1.0f/PIXELS_PER_METREf; bodyDef.userData = this; if ( m_attributes & ATTRIB_SLEEPING ) { bodyDef.isSleeping = true; } m_body = world.CreateBody( &bodyDef ); for ( int i=1; i<n; i++ ) { BoxDef boxDef; boxDef.init( m_shapePath.point(i-1), m_shapePath.point(i), m_attributes ); m_body->CreateShape( &boxDef ); } m_body->SetMassFromShapes(); } transform(); }
void JointPlatform::SetWorld(b2World & world) { _pBody = world.CreateBody(&_bodyDef); _pBody->CreateFixture(&_fixtureDef); _pJointBody = world.CreateBody(&_jointBodyDef); _pJointBody->CreateFixture( &_jointFixtureDef); _jointDef.bodyA = _pBody; _jointDef.bodyB = _pJointBody; _jointDef.localAnchorA = _pBody->GetLocalCenter() ; _jointDef.localAnchorB = _pJointBody->GetLocalCenter(); _pJoint = (b2RevoluteJoint *)world.CreateJoint(&_jointDef); }
Rope::Rope(b2World& aWorld, float aX, float aY) : myWorld(aWorld) { b2Body* lastBody; for (int i = 0; i < 10; i++) { float ROPE_LENGTH = 0.2; float ROPE_WIDTH = 0.01; b2BodyDef dropboxDef2; dropboxDef2.position = b2Vec2(aX, aY + i * ROPE_LENGTH); dropboxDef2.linearDamping = 0.8f; //dropboxDef.angle = 0.2; if (i != 0) { dropboxDef2.type = b2_dynamicBody; } b2PolygonShape dropboxShape2; dropboxShape2.SetAsBox(ROPE_WIDTH / 2, ROPE_LENGTH / 2); b2Body* body2 = aWorld.CreateBody(&dropboxDef2); body2->CreateFixture(&dropboxShape2, 0.05f)->SetUserData( (UserData*) this); if (i != 0) { b2RevoluteJointDef jointDef; b2Vec2 anchor = (lastBody->GetPosition() + body2->GetPosition()); anchor *= 0.5; jointDef.Initialize(lastBody, body2, anchor); jointDef.collideConnected = false; jointDef.enableLimit = true; jointDef.upperAngle = 0.8; jointDef.lowerAngle = -0.8; b2RevoluteJoint* joint = (b2RevoluteJoint*) aWorld.CreateJoint( &jointDef); myJoints.push_back(joint); } myParts.push_back(body2); lastBody = body2; } mySprite.LoadTGA("data/rope.tga"); }
void Box2dApp::setup() { b2Vec2 gravity( 0.0f,0.1f ); mWorld = new b2World( gravity ); mWorld->SetContactListener(&myContactListenerInstance); mGround = ground(mWorld); }