0
votes

I'm developing a top down style game where the user can control multiple characters at one time. These characters can move in any direction. There are static bodies (walls, buildings) that the characters can bump into using Box2d for collision detection. The user can move the camera around by dragging his finger across the screen. This will move the CCLayer and any containing CCSprite objects that I added to the layer.

This worked just fine, but then I realized that moving the layer and the sprites did not move the Box2d bodies that they were attached to. The bodies continue moving in their original projections. I've been searching for an answer, but it doesn't seem like anyone has had this problem which leads me to believe that my approach may be off.

I considered moving the camera around instead of the layer, but after a lot of google searching it seems that most people frown upon that idea. So does anyone have any suggestions?

1

1 Answers

0
votes

My approach was off a bit. I'm not using Box2D for anything other than collision detection, so I should not have been using it to move my sprites around the screen. I updated my code to have cocos2d handle the positioning of my sprites and then I updated the box2d body locations based on the sprite's locations.

Here's a tutorial I found helpful: http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone

That tutorial explains how to update the body locations based on your cocos2d sprites' locations. In addition since I was moving the layer around I had to make a slight modification to the tutorials code. Here it is:

CCSprite *sprite = (CCSprite*)b->GetUserData();
CGPoint pos = [gameLayer convertToWorldSpace:[sprite position]];
b2Vec2 b2Position = b2Vec2(pos.x/PTM_RATIO, pos.y/PTM_RATIO);
float32 b2Angle = -1 * CC_DEGREES_TO_RADIANS(sprite.rotation);
b->SetTransform(b2Position, b2Angle);

The method convertToWorldSpace:(CGPoint)point takes the location of the sprite and converts it's location to world space based on how you have the CCLayer position moved around the screen.

I hope someone else finds this helpful!