Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML\Graphics.hpp>
- #include <Box2D\Box2D.h>
- /** We need this to easily convert between pixel and real-world coordinates*/
- static const float SCALE = 30.f;
- /** Create the base for the boxes to land */
- void CreateGround(b2World& World, float X, float Y);
- /** Create the boxes */
- void CreateBox(b2World& World, int MouseX, int MouseY);
- int main()
- {
- /** Prepare the window */
- sf::RenderWindow Window(sf::VideoMode(800, 600, 32), "Test");
- Window.SetFramerateLimit(60);
- /** Prepare the world */
- b2Vec2 Gravity(0.f, 9.8f);
- b2World World(Gravity);
- CreateGround(World, 400.f, 500.f);
- /** Prepare textures */
- sf::Texture GroundTexture;
- sf::Texture BoxTexture;
- GroundTexture.LoadFromFile("ground.png");
- BoxTexture.LoadFromFile("box.png");
- while (Window.IsOpened())
- {
- if (sf::Mouse::IsButtonPressed(sf::Mouse::Left))
- {
- int MouseX = sf::Mouse::GetPosition(Window).x;
- int MouseY = sf::Mouse::GetPosition(Window).y;
- CreateBox(World, MouseX, MouseY);
- }
- World.Step(1/60.f, 8, 3);
- Window.Clear(sf::Color::White);
- int BodyCount = 0;
- for (b2Body* BodyIterator = World.GetBodyList(); BodyIterator != 0; BodyIterator = BodyIterator->GetNext())
- {
- if (BodyIterator->GetType() == b2_dynamicBody)
- {
- sf::Sprite Sprite;
- Sprite.SetTexture(BoxTexture);
- Sprite.SetOrigin(16.f, 16.f);
- Sprite.SetPosition(SCALE * BodyIterator->GetPosition().x, SCALE * BodyIterator->GetPosition().y);
- Sprite.SetRotation(BodyIterator->GetAngle() * 180/b2_pi);
- Window.Draw(Sprite);
- ++BodyCount;
- }
- else
- {
- sf::Sprite GroundSprite;
- GroundSprite.SetTexture(GroundTexture);
- GroundSprite.SetOrigin(400.f, 8.f);
- GroundSprite.SetPosition(BodyIterator->GetPosition().x * SCALE, BodyIterator->GetPosition().y * SCALE);
- GroundSprite.SetRotation(180/b2_pi * BodyIterator->GetAngle());
- Window.Draw(GroundSprite);
- }
- }
- Window.Display();
- }
- return 0;
- }
- void CreateBox(b2World& World, int MouseX, int MouseY)
- {
- b2BodyDef BodyDef;
- BodyDef.position = b2Vec2(MouseX/SCALE, MouseY/SCALE);
- BodyDef.type = b2_dynamicBody;
- b2Body* Body = World.CreateBody(&BodyDef);
- b2PolygonShape Shape;
- Shape.SetAsBox((32.f/2)/SCALE, (32.f/2)/SCALE);
- b2FixtureDef FixtureDef;
- FixtureDef.density = 1.f;
- FixtureDef.friction = 0.7f;
- FixtureDef.shape = &Shape;
- Body->CreateFixture(&FixtureDef);
- }
- void CreateGround(b2World& World, float X, float Y)
- {
- b2BodyDef BodyDef;
- BodyDef.position = b2Vec2(X/SCALE, Y/SCALE);
- BodyDef.type = b2_staticBody;
- b2Body* Body = World.CreateBody(&BodyDef);
- b2PolygonShape Shape;
- Shape.SetAsBox((800.f/2)/SCALE, (16.f/2)/SCALE);
- b2FixtureDef FixtureDef;
- FixtureDef.density = 0.f;
- FixtureDef.shape = &Shape;
- Body->CreateFixture(&FixtureDef);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement