Help with design issue
Here is my problem.
I'm using a physics library called Box2D. I'm able to hook up a listener that will tell me when 2 fixtures collide.
Essentially the way Box2D works is by creating b2Bodies. Therefore, I only know which b2Body the fixture that collided belongs to. In my game, I have an Entity, and from that I have a PhisicsEntity. A PhysicsEntity holds a pointer to a b2Body. It also has a sendMessage method that comes from Entity. The problem is, from the b2Body, how do I send the PhysicsEntity a collision message. What I thought of doing was to set the userData void* of the b2Body to its corresponding PhysicsEntity. It seems very wrong to have to cast a void* to do this though.
Is there a better way that I could very quickly know the Physics Entity associated with the b2Body witho开发者_如何学运维ut casting or lookup?
Thanks
This is exactly the purpose that fields like that userData field are for — to refer to your application's data related to the library's object. This is an entirely appropriate use of void *
.
If you were asking about C, I would say that you should also not have to use any casts, as converting to and from void *
can be done without any casts and needing to use a cast is a sign of a possible problem, but if I recall correctly C++ requires those casts (I do not use C++ enough to be sure).
That's actually exactly what the userData pointer is meant for. It's a fairly standard paradigm - look at functions such as pthread_create or CreateThread for another example.
If you encounter a library that doesn't allow you to use a void * (or not safely - such as storing it locally as an int) then you can use an std::map to resolve the type. That's slower and with much more overhead though.
精彩评论