sample SFML / BOX2D


SUBMITTED BY: Guest

DATE: Nov. 12, 2013, 2:44 a.m.

FORMAT: Text only

SIZE: 2.5 kB

HITS: 726

  1. #include <SFML/Graphics.hpp>
  2. #include <Box2D/Box2D.h>
  3. #include <stdio.h>
  4. #define PPM 30 // Pixel Per Meters
  5. using namespace sf;
  6. int main()
  7. {
  8. bool running = true;
  9. RenderWindow app(VideoMode(800,600,32),"First Test",Style::Close);
  10. Shape box = Shape::Rectangle(500,20,600,70,Color::White);
  11. Shape ground = Shape::Line(50,550,750,200,1,Color::Red);
  12. // set up the world
  13. b2Vec2 gravity(0.0f,9.8f);
  14. b2World *myWorld = new b2World(gravity,true);
  15. // box body definition
  16. b2BodyDef boxBodyDef;
  17. b2Vec2 boxVelocity;
  18. boxVelocity.Set(0.0f,10.0f);
  19. boxBodyDef.type = b2_dynamicBody;
  20. boxBodyDef.position.Set(500,20);
  21. boxBodyDef.linearVelocity = boxVelocity;
  22. // line body definition
  23. b2BodyDef lineBodyDef;
  24. lineBodyDef.type = b2_staticBody;
  25. lineBodyDef.position.Set(50,550);
  26. // create the bodies
  27. b2Body *boxBody = myWorld->CreateBody(&boxBodyDef);
  28. b2Body *lineBody = myWorld->CreateBody(&lineBodyDef);
  29. // create the shapes
  30. b2PolygonShape boxShape,lineShape;
  31. boxShape.SetAsBox(50.0f/PPM,25.0f/PPM);
  32. lineShape.SetAsEdge(b2Vec2(50/PPM,550/PPM),b2Vec2(750/PPM,200/PPM));
  33. // add fixtures
  34. b2FixtureDef boxFixtureDef,lineFixtureDef;
  35. boxFixtureDef.shape = &boxShape;
  36. lineFixtureDef.shape = &lineShape;
  37. boxFixtureDef.density = 1;
  38. boxBody->CreateFixture(&boxFixtureDef);
  39. lineBody->CreateFixture(&lineFixtureDef);
  40. float timeStep = 1.0f / 20.0f; // 20fps
  41. int velIter = 8;
  42. int posIter = 3;
  43. while(running)
  44. {
  45. Event event;
  46. while(app.GetEvent(event))
  47. {
  48. if(event.Type == Event::Closed)
  49. running = false;
  50. }
  51. myWorld->Step(timeStep, velIter, posIter);
  52. b2Vec2 pos = boxBody->GetPosition();
  53. printf("%f %f\n",pos.x, pos.y);
  54. box.SetPointPosition(0,pos.x, pos.y);
  55. box.SetPointPosition(1,pos.x+100,pos.y);
  56. box.SetPointPosition(2,pos.x+100,pos.y+50);
  57. box.SetPointPosition(3,pos.x,pos.y+50);
  58. app.Clear();
  59. app.Draw(box);
  60. app.Draw(ground);
  61. app.Display();
  62. }
  63. app.Close();
  64. delete myWorld;
  65. return EXIT_SUCCESS;
  66. }

comments powered by Disqus