Hello bros
I joined this forum a few weeks ago and started to learn basics about game programming.. Last night I tried to get this and do a simple experiment with SFML and Box2d. Here is some code:
Block.cpp
const int PPM = 60;
Block::Block(b2World *world, float width, float height, sf::Vector2f position, sf::Color color, float mu, bool dynamic, float e)
{
rectangle = sf::RectangleShape( sf::Vector2f(width, height) );
rectangle.setPosition(position);
rectangle.setFillColor(color);
// Define la entidad que se dibuja en la pantalla
// Definicion del cuerpo
b2BodyDef bodydef;
bodydef.position.Set(position.x / PPM , position.y/PPM );
if (dynamic)
bodydef.type = b2_dynamicBody;
// La unica parte del cuerpo es un rectangulo
b2FixtureDef fixturedef;
b2PolygonShape shape;
shape.SetAsBox(width/(2*PPM), height / (2*PPM) );
fixturedef.shape = &shape;
fixturedef.friction = mu;
fixturedef.density = 1.0f;
fixturedef.restitution = e;
// Inicializamos el cuerpo para la simulacion
body = world->CreateBody(&bodydef);
body->CreateFixture(&fixturedef);
// cout << body->GetPosition().x << endl;
}
Block.h
class Block
{
private:
b2Body *body;
sf::RectangleShape rectangle;
public:
// Constructor
Block(b2World *world, float width, float height, sf::Vector2f position, sf::Color color, float mu, bool dynamic, float e);
// Obtiene el objeto
b2Body* GetBody();
// Obtiene la forma
sf::Shape & GetShape();
// Actualiza el estado en pantalla
void Update();
};
As you can see I tried to make an object such that When I call the constructor I create a rectangle shape and a body. There is another method to update the position of the rectangle shape with the position of the body (in box2d). In the main I have something like this
std::vector<Block> bloques;
bloques.push_back( Block(world, 900.0f, 50.0f, sf::Vector2f(0, height-50), blanco, 0.5f, false, 0) );
bloques.push_back(Block(world, 50.0f, 50.0f, sf::Vector2f(0, 0), azul, 0.5f, true, 0.5f));
bloques.push_back(Block(world, 30.0f, 25.0f, sf::Vector2f(51, 0), azul, 0.5f, true, 0.4f));
Greetings
EDIT: I solved the problem, after hours of studying the case I found a solution. Give a chance to edit again a post the correct code with an explanation, so other beginners can use this code as a test!