Game Development Reference
In-Depth Information
Sprite plus b2Body equal to b2Sprite
The most common way to work with
b2Body
objects in Cocos2d-x is to combine them
with sprites. In the games I'll show you, I created a class called
b2Sprite
that extends
sprite with the addition of a
_body
member property that points to its very own
b2Body
.
I also add a few helper methods to deal with our pesky
PTM_RATIO
. Feel free to add as
many of these as you think necessary.
b2Body
objects have an incredibly helpful property called
userData
. You can store any-
thing you wish inside it and the bodies will carry it with them throughout the simulation.
So, what most developers do is that they store inside the body's
userData
property a ref-
erence to the instance of sprite wrapping it. So
b2Sprite
knows about its body, and the
body knows about its
b2Sprite
.
Tip
As a matter of fact, composition is key when working with Box2D. So, when designing
your games, make sure every object knows of every other object or can get to them quickly.
This will help immensely.