Reputation: 281
I have previously used Box2D, so this code I'm using is already functional on another project, the only major difference is that the world isn't being passed as a paremeter, it's given as a Global Pointer.
When I apply the Linear Velocity (which I have already tried from 1 to 99999 and still nothing), not even the position on world getting it by Obj1->Body2D->GetPosition().x;
will have any change.
Main:
GameObject Obj1 = new GameObject(iVec2(500), iVec2(30));
void Update() {
Obj1->b2_body->SetLinearVelocity(b2Vec2(5, 0));
//Still same Position on Obj1
//Camera Update
Obj1->Render(*Renderer);
}
Script 1:
std::unique_ptr<b2World> World = std::make_unique<b2World>(b2Vec2(0.0f, 9.81f));
Script 2:
extern std::unique_ptr<b2World> World;
GameObject::GameObject(iVec2 position, iVec2 size, Texture sprite, iVec3 color)
:Position(iVec2(position.x / 128.0f, position.y / 128.0f)), Size(iVec2(size.x / 128.0f, size.y / 128.0f)) {
this->RenderPosition = position;
this->RenderSize = size;
b2BodyDef b2d_BodyDef;
b2d_BodyDef.type = b2_dynamicBody;
b2d_BodyDef.position.Set(Position.x, Position.y);
b2d_Body = World->CreateBody(&b2d_BodyDef);
b2PolygonShape b2d_BoxShape;
b2d_BoxShape.SetAsBox(Size.x / 2, Size.y / 2);
b2FixtureDef b2d_FixtureDef;
b2d_FixtureDef.shape = &b2d_BoxShape;
b2d_FixtureDef.density = 1.0f;
b2d_Fixture = b2d_Body->CreateFixture(&b2d_FixtureDef);
}
void GameObject::Render(Renderer2D & renderer) {
float tempPosX = this->b2d_Body->GetPosition().x;
float tempPosY = this->b2d_Body->GetPosition().y;
this->RenderPosition = iVec2((tempPosX - Size.x / 2) * 128.0f, (tempPosY - Size.y / 2) * 128.0f);
this->RenderSize = iVec2(Size.x * 128.0f, Size.y * 128.0f);
renderer.Render(this->Sprite, this->RenderPosition, this->RenderSize, this->RealRotation, this->Color);
}
Upvotes: 0
Views: 98
Reputation: 3123
Per the conversation in the comments... if the world Step
method isn't called, then object positions won't update.
Add a call like:
World->Step(timeStep, velocityIterations, positionIterations);
Put it in a loop to get object positions to update based on their properties like their velocities.
iforce2d has produced a tutorial on Box2D worlds (including use of their step method) that I recommend for anyone who wants to learn more about the Box2D b2World
class.
Hope this helps!
Upvotes: 1