As the title says. my Box2D bodies seem to be out of sync with the sprites.
The sprites move when the body does, however it isn't centered.
Not sure if this is because of the body's size or if it's the position that isn't correct.
PPM is the conversion number form meters to pixels :
#define PPM 20
And this is what my sprite creation function looks like :
Sprite::Sprite(std::string id, std::string filePath, Vector2 position, Vector2 size, float _density, float _friction, b2BodyType type)
{
spriteId = id;
surface = SDL_LoadBMP(filePath.c_str());
if (surface == nullptr)
{
Errors::Error("Failed to load image!", __FILE__, __LINE__);
return;
}
x = position.x;
y = position.y;
surface->w = size.x;
surface->h = size.y;
width = size.x;
height = size.y;
texture = SDL_CreateTextureFromSurface(Window::GetRenderer(), surface);
SDL_FreeSurface(surface);
surface = nullptr;
density = _density;
friction = _friction;
bodyDef.type = type;
bodyDef.gravityScale = 9.8f;
bodyDef.position.Set(x, y);
b2World* world = World::GetWorld();
body = World::GetWorld()->CreateBody(&bodyDef);
shape.SetAsBox(width / 2, height / 2);
fixtureDef.shape = &shape;
fixtureDef.density = density;
fixtureDef.friction = friction;
body->CreateFixture(&fixtureDef);
}
And this is my sprite drawing function :
void Sprite::Draw()
{
//std::cout << body->GetPosition().x << " " << body->GetPosition().y << std::endl;
x = body->GetPosition().x / PPM;
y = body->GetPosition().y / PPM;
SDL_Rect rect;
rect.x = x;
rect.y = y;
rect.w = width;
rect.h = height;
if (SDL_RenderCopy(Window::GetRenderer(), texture, NULL, &rect) < 0)
{
Errors::Error("Failed to render texture : " + spriteId, __FILE__, __LINE__);
return;
}
}
I'm very confused on when I should use / PPM or * PPM...
Edit :
I took a break form the project for a while, still couldn't understand what was wrong.
Here's a image to "visualize" what I mean and what my problem is.
The values in the console are the positions of each body in the world.
I'm still using the exact same code, except that I set my PPM to 1.
Edit 2 :
After even more printing out values, it seems like the bodies aren't colliding at all? o.o
Might just be stupid though, I'm really tired as I'm testing this.
Here's the "new" values :