Cocos2d : Shooting a ball in the direction of the mouse click/Touch

285 views Asked by At

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);     
    }
1

There are 1 answers

3
Anselm Stordeur On

Do you want the Ball flying constantly or accelerated? For constant speed I would try to use something like this:

CCPoint location = touch->getLocation();
CCPoint ballLoc = ball->getPosition();
CCSize winSize = CCDirector::sharedDirector()->getVisibleSize();

float dX = location.x - ballLoc.x;   //delta between touch and ball
float dX = location.y - ballLoc.y;

float c =  sqrtf((dX * dX) + (dY*dY));   //distance with pythagoras
float cmax = sqrtf((winSize.width * winSize.width) + (winSize.height*winSize.height));   //max Distance when clicking in the bottom right corner the distance is max
float r = cmax / c;   //value to multiply distance

float destX = ballLoc.x + r*dX; //destination is ball location + r*delta
float destY = ballLoc.y + r*dY;

projectile->runAction(CCMoveTo::create(2.0, ccp(realX, realY));

Optional you can add a duration depending on the distance.

I hope this helps.