views:

1065

answers:

2

Hello stackoverflow community !

I am trying to figure out how to architect my game using cocos2d.

My problem is that cocos2d's physics engine (i'm talking about chipmunk) lies in a world behind sprites.

When I move the sprite, I'm wondering if I should

*1) be moving it by applying forces on the physics body behind it

OR

2) if i should just simulate movements through code then use physics only when a collision occurs.*


I know you may say that it's up to me. But what was the intended behavior as cocos2d iphone was developed?

I thank you in advance <3

+2  A: 

To keep it within the chipmunk system you would apply forces/impulses. There are examples of folks taking control of moving the sprite with their own code, getting the body to follow the sprite then giving control of the body back to the chipmunk simulation.

Quite a few people also just use chipmunk for collision detection and control sprite movement with their own code entirely. This can be done by adding the body to the chipmunk space but not adding the shape to the space.

Here are some discussions on the subject.. I can't post them as hyperlinks because I am a new user..

"http://groups.google.com/group/cocos2d-iphone-discuss/browse_thread/thread/ae37e90eac059135/081da9bcefec76ba?#081da9bcefec76ba"

"http://www.cocos2d-iphone.org/forum/topic/877"

"http://jeanbombeur.com/content/2009-07-08-synchronizing-sprites-positions-and-rotations-between-chipmunk-and-cocos2d"

Welcome and good luck!

PS
There is also a way to turn on a Chipmunk mode that gives you a little more freedom over what you can control but at the cost of a more realistic simulation.

+1  A: 

For sprites you want want to keep in line with shapes you need to tie the sprite as the shape->data when creating the shape.

Then use the each shape function

cpSpaceHashEach(space->activeShapes, &functioncallback, data)

In your callback function using the shape->data you can update the sprites location to the position of the body attached to the shape

Sprite s = shape->data
[s setPosition:cpv(body->p.x,body->p.y)];

use a Cocos schedule to call cpSpaceStep() and cpSpaceHashEach(). Make sure you don't call them each frame or you will have problems with things staying in sync.

I use

[self schedule:@selector(step:) interval:(1.0f/60.0f)/3]

This way my sprites all follow the chimpmunk data and performing the physics with no extra work from me.

Armychimp