Playing around with a ball(stationary) that's on the top left hand corner of the layout. When I use a mouse click I want the ball to be hit by a force and pass through the mouse click. The mouse click can be anywhere on the layout other than on the ball. I used to have this working, using #1 from the code below. But its broken at the moment. When I click the ball at say 90 degrees, it shoots a little bit away from the mouse click like say 90 + x. the angle is off by a 10 degrees or so.
I created the basic level using levelhelper2 toolset to layout the sprites.
/*--------------- touchEnded ------------------------------------*/
-(void)touchEnded:(CCTouch *)touch withEvent:(CCTouchEvent *)event
{
ball = (LHSprite*)[self childNodeWithName:@"Ri"];
ball.anchorPoint = ccp(0.5f,0.5f);
body = [ball box2dBody];
pos = body->GetPosition();
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGPoint shootVector = ccpSub( location, ball.position );
/* #1 Tried this first.
b2Vec2 force = b2Vec2(shootVector.x ,shootVector.y);
force.Normalize();
force *= 1.5f;
*/
/* #2 : Try this version */
CGFloat shootAngle = ccpToAngle(shootVector);
float power = 10;
float x1 = -1 * CC_RADIANS_TO_DEGREES(cos(shootAngle));
float y1 = -1 * CC_RADIANS_TO_DEGREES(sin(shootAngle));
b2Vec2 force = b2Vec2(x1* power,y1* power);
body->ApplyLinearImpulse(force, pos, 1);
}
Do you want the Ball flying constantly or accelerated? For constant speed I would try to use something like this:
Optional you can add a duration depending on the distance.
I hope this helps.