How to shoot a bullet in the direction of touch in Box2D iphone?

By | January 30, 2011

write the below code in “ccTouchesBegan” function and you are done.
Here the ballBody represents the bullet body. You can increase the power variable to increase bullet speed.

[java]
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGPoint shootVector = ccpSub(location, ball.position);
CGFloat shootAngle = ccpToAngle(shootVector);
CGPoint normalizedShootVector = ccpNormalize(shootVector);
CGPoint overshotVector = ccpMult(normalizedShootVector, 420);
CGPoint offscreenPoint = ccpAdd(ball.position, overshotVector);

int power = 100;

b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(ball.position.x/PTM_RATIO, ball.position.y/PTM_RATIO);
ballBodyDef.userData = ball;
b2Body *ballBody = world->CreateBody(&ballBodyDef;);
b2CircleShape circle;
circle.m_radius = 7.0/PTM_RATIO;
float x1 = cos(shootAngle);
float y1 = sin(shootAngle);
b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 80.0f;
ballShapeDef.friction = 0.0f; // We don’t want the ball to have friction!
ballShapeDef.restitution = 1.0f;
ballBody->CreateFixture(&ballShapeDef;);
b2Vec2 force = b2Vec2(x1* power,y1* power);
ballBody->ApplyLinearImpulse(force, ballBodyDef.position);
[/java]

Leave a Reply

Your email address will not be published. Required fields are marked *