Game Objects setup in cocos2d + box2d

2019-08-20 05:58发布

问题:

I am having a design issue, this may be due to the fact that i don't fully understand cocos2d and box2d yet.

I want to create game objects that have a CCSprite(image data) and a b2Body(physics), Would i be right to make an encapsulating object that contains both? if i did this this would enable me to make changes to the CCSprite

OR

as i have seen in the example code the b2Body has a userData variable which the sprite is set as. Then with this method i would only need to have a single pointer to the physics objects which would take care of the CCSprite.

Thx in advance.

回答1:

My preferred way of doing it is to encapsulate both in an Actor object. My Actor object is also responsible for updating the CCSprite position/rotation based on the b2Body data. Then I use that Actor object as the userData in the b2Body. Having the Actor as the userData is helpful when iterating over bodies in contact listeners.



回答2:

A simple solution is to set the body's userData member to point to the sprite, and the sprite's userData member to point to the body. This way you can access them both in an easy and convinient way. Then you shouldn't need to encapsulate the sprite and body objects in an actor either.