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.

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;
b2Vec2 force = b2Vec2(x1* power,y1* power);
ballBody->ApplyLinearImpulse(force, ballBodyDef.position);

Leave a Reply

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




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.