Advertisement
Evgenistan

box2d

Jan 29th, 2023 (edited)
989
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <Box2D/Box2D.h>
  3. #include <SFML/Graphics.hpp>
  4.  
  5.  
  6. int main()
  7. {
  8.     sf::RectangleShape rectRender(sf::Vector2f(100,50));
  9.     b2World world(b2Vec2(0, 100));
  10.     world.SetGravity(b2Vec2(0, 100));
  11.     b2BodyDef boxDef;
  12.     boxDef.type = b2_kinematicBody;
  13.     boxDef.position.Set(50, 100);
  14.     b2FixtureDef boxFixDef;
  15.     boxFixDef.friction = 0;
  16.     boxFixDef.restitution = 0;
  17.     b2PolygonShape boxShape;
  18.     boxShape.SetAsBox(50, 25);
  19.     boxFixDef.shape = &boxShape;
  20.     b2Body* body = world.CreateBody(&boxDef);
  21.     body->CreateFixture(&boxFixDef);
  22.     body->SetLinearDamping(0);
  23.  
  24.  
  25.     sf::RectangleShape rectRender2(sf::Vector2f(100, 50));  rectRender2.setFillColor(sf::Color::Red);
  26.     b2BodyDef boxDef2;
  27.     boxDef2.type = b2_dynamicBody;
  28.     boxDef2.position.Set(50, 10);
  29.     b2FixtureDef boxFixDef2;
  30.     boxFixDef2.restitution = 0;
  31.     boxFixDef.friction = 0;
  32.     boxFixDef2.density = 20;
  33.     b2PolygonShape boxShape2;
  34.     boxShape2.SetAsBox(50, 25);
  35.     boxFixDef2.shape = &boxShape;
  36.     b2Body* body2 = world.CreateBody(&boxDef2);
  37.     body2->CreateFixture(&boxFixDef2); 
  38.     body2->SetLinearDamping(0);
  39.  
  40.  
  41.     sf::RenderWindow window(sf::VideoMode(1280, 720), "Box2D Test");
  42.     window.setFramerateLimit(60);
  43.     while (window.isOpen())
  44.     {
  45.         world.Step(1 / 60.f, 8, 3);
  46.         sf::Event event;
  47.         while (window.pollEvent(event))
  48.         {
  49.             if (event.type == sf::Event::Closed)
  50.                 window.close();
  51.             if (event.type == sf::Event::KeyPressed)
  52.             {
  53.                 body->SetTransform(b2Vec2(body->GetPosition().x + 10, body->GetPosition().y), 0);
  54.             }
  55.         }
  56.  
  57.         window.clear();
  58.         rectRender.setPosition(body->GetPosition().x, body->GetPosition().y);
  59.         rectRender2.setPosition(body2->GetPosition().x, body2->GetPosition().y);
  60.         window.draw(rectRender);
  61.         window.draw(rectRender2);
  62.         window.display();
  63.         std::cout << body2->GetLinearVelocity().y << std::endl;
  64.     }
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement