Skip to content

Instantly share code, notes, and snippets.

@8Observer8
Created March 29, 2023 18:05
Show Gist options
  • Save 8Observer8/bdff78503d99c383be723f8a0ad5443b to your computer and use it in GitHub Desktop.
Save 8Observer8/bdff78503d99c383be723f8a0ad5443b to your computer and use it in GitHub Desktop.
Keeping User Data for Box2D
// https://coliru.stacked-crooked.com/a/7765d15fe603a3d9
// https://gamedev.stackexchange.com/a/196955/115807
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <map>
struct b2Fixture;
struct MyFixtureUserDataType
{
int myVal {};
b2Fixture* mFixture {};
};
struct b2FixtureUserData
{
b2FixtureUserData()
{
pointer = 0;
}
uintptr_t pointer;
};
struct b2FixtureDef
{
b2FixtureUserData userData;
};
struct b2Fixture
{
b2Fixture( const b2FixtureDef* def )
{
m_userData = def->userData;
}
b2FixtureUserData& GetUserData() { return m_userData; }
b2FixtureUserData m_userData;
};
int main()
{
std::map<uintptr_t, std::unique_ptr<MyFixtureUserDataType>> allMyThings;
auto myThing = std::make_unique<MyFixtureUserDataType>();
myThing->myVal = 3;
b2FixtureDef def;
def.userData.pointer = reinterpret_cast<uintptr_t>( myThing.get() );
std::unique_ptr<b2Fixture> fix = std::unique_ptr<b2Fixture>( new b2Fixture( &def ) ); // we do this for the sake of this example.
myThing->mFixture = fix.get();
allMyThings[reinterpret_cast<uintptr_t>( fix.get() )] = std::move( myThing );
myThing = nullptr;
// do something to access your data
std::cout << reinterpret_cast<MyFixtureUserDataType*>( fix->GetUserData().pointer )->myVal;
// We no longer need it
fix.reset();
allMyThings.erase( reinterpret_cast<uintptr_t>( fix.get() ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment