I know that fast moving bodies in Box2d world cause tunneling effect and pass through each other. Solution is to define the bodies as bullets. I did that but bodies sometimes still cross each other especially if encounter point is not exactly towards middle and bodies partially overlap while crossing. Any solution?
This is how I am making all the bodies:
redBall = [CCSprite spriteWithFile:@"red-ball" rect:CGRectMake(0, 0, 34, 34)];
redBall.tag = 1;
[self addChild:redBall];
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set((winSize.width/2)/PTM_RATIO, redBall.position.y/PTM_RATIO);
ballBodyDef.userData = redBall;
ballBodyDef.bullet = true;
_ballBody = _world->CreateBody(&ballBodyDef);
// Create circle shape
b2CircleShape circle;
circle.m_radius = 17.0/PTM_RATIO;
// Create shape definition and add to body
b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 0.2f;
ballShapeDef.friction = 0.0f;
ballShapeDef.restitution = 1.0f;
_ballFixture = _ballBody->CreateFixture(&ballShapeDef);
I am moving this ball in TouchesEnd as:
- (void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGPoint shootVector = ccpSub(location, striker.position);
CGFloat shootAngle = ccpToAngle(shootVector);
CGPoint normalizeShootVector = ccpNormalize(shootVector);
float x1 = - cos(shootAngle);
float y1 = - sin(shootAngle);
int power = 0;
float dist =ccpDistance(location, redBall.position);
if (dist >= 200)
power = 20;
else if (dist >= 100)
power = 10;
else if (dist >=75)
power = 7;
else if (dist >= 60)
power = 4;
else if (dist >= 50)
power = 3;
else if (dist >= 35)
power = 2;
else
power = 1;
b2Vec2 force = b2Vec2(x1*power, y1*power);
_ballBody->ApplyLinearImpulse(force,ballBodyDef.position);
}
It's simply the calculation of distance of touch point from the ball, finding power to apply on ball according to the distance and moving the ball in the direction of touch. And this ball collides with any other ball that comes in it's way.