Box2D Weird collision behavior

by GigaNova   Last Updated September 10, 2019 23:13 PM

I'll let the gif speak first. enter image description here As you can see, the small cube just kinda floats there like it has a forcefield. This weird glitch only happens with small cubes, smaller than 60 pixels for some reason. It's 32x32. And I have no clue why this happens, at all. I've debugged and debugged, but I am at my end.

Box class

#include "Box.h"
#include <SDL/SDL_image.h>
#include <Box2D/Dynamics/b2World.h>
#include <iostream>
#include "World.h"

Box::Box(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer, b2World* _world) : m_image(IMG_LoadTexture(_renderer, _textureName.c_str()))
{
    SDL_QueryTexture(m_image, nullptr, nullptr, nullptr, nullptr);

    m_bounds.x = _x;
    m_bounds.y = _y;
    m_bounds.w = _width;
    m_bounds.h = _height;

    m_bodyDef.type = b2_dynamicBody;
    m_bodyDef.position.Set(_x / World::PPM, _y / World::PPM);
    m_body = _world->CreateBody(&m_bodyDef);

    m_polygon.SetAsBox((_width / World::PPM) / 2.0f, (_height / World::PPM) / 2.0f);

    m_fixture.shape = &m_polygon;
    m_fixture.density = 1.0f;
    m_fixture.friction = 0.3f;

    m_body->CreateFixture(&m_fixture);
}

void Box::draw(SDL_Renderer* _render) const
{
    SDL_Point center;
    center.x = m_bounds.w - (m_bounds.w / 2);
    center.y = m_bounds.h - (m_bounds.h / 2);

    const auto angle = (180 * m_body->GetAngle()) / M_PI;

    SDL_RenderCopyEx(_render, m_image, nullptr, &m_bounds, angle, &center, SDL_FLIP_NONE);
}

void Box::update()
{
    m_bounds.x = m_body->GetPosition().x * World::PPM;
    m_bounds.y = m_body->GetPosition().y * World::PPM;
}

World class

#include "World.h"
#include "Box2D/Box2D.h"

World::World() : m_world(b2Vec2(0.0f, 9.8)), m_timeStep(1.0f / 60.0f)
{
    m_groundBodyDef.position.Set(400.0f / PPM, 590.0f / PPM);
    m_groundBody = m_world.CreateBody(&m_groundBodyDef);

    b2PolygonShape groundBox;
    groundBox.SetAsBox(400.0f / PPM, 20.0f / PPM);
    m_groundBody->CreateFixture(&groundBox, 2.0f);
}

void World::update()
{
    m_world.Step(m_timeStep, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
    for (auto box : m_boxes)
    {
        box->update();
    }
}

void World::render(SDL_Renderer* m_renderer)
{
    for(auto box : m_boxes)
    {
        box->draw(m_renderer);
    }
}

void World::createBox(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer)
{
    m_boxes.push_back(new Box(_textureName, _x, _y, _width, _height, _renderer, &m_world));
}

If anybody has any idea why this might happen, please let me know. Thank you.



Related Questions


Updated July 25, 2019 21:13 PM

Updated August 30, 2017 17:13 PM

Updated August 08, 2015 14:05 PM

Updated March 11, 2017 23:13 PM

Updated May 25, 2017 17:13 PM