Question

Using cocos2d and box2d , i have a few bodies that i need them to be attracted to each other, and a few others to reject one another. This means that when they are close the attract like magnet, or reject and pushed away.

Do i have to program it in the hard way (checking distance between them than applying forces when they are close) , or there is a simpler way for that ?

thanks a lot .

Was it helpful?

Solution

Do I have to program it in the hard way?

Yep. There is nothing built into Box2d (or cocos2d) currently to do this.


Edit

Pertaining to your comment:

do you have an idea how to even start checking for each body all his close bodies and distances between all ?

It'll depend on how many bodies you have as to which technique you'll want to use. If you have a LOT of bodies, you might want to look at quad-trees to divide up your space and quickly ignore bodies that aren't close.

If you don't have that many, you can iterate your bodies in O(n^2) time with a naïve, but comparatively simple double for loop.

NB: This is by no means a complete solution, you should consider it pseudo code as it won't be compilable.

for (b2Body *b in myBodies)
{
    for (b2Body *b2 in myBodies)
    {
        if (b == b2) continue;
        float distance = b2Distance(b->GetWorldCenter(), b2->GetWorldCenter());
        if (shouldAttract)
        {
            float angle1 = b2Cross(b->GetWorldCenter(), b2->GetWorldCenter());
            float angle2 = b2Cross(b2->GetWorldCenter(), b->GetWorldCenter());
            b->ApplyForce(distance * angle1); 
            b2->ApplyForce(distance * angle2); 
        }
        /* else if (shouldRepel) */
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top