2015-06-08 82 views
0

使用位於版面左上角的球(靜止)進行遊戲。當我使用鼠標點擊時,我希望球被一個力擊中並通過鼠標點擊。鼠標點擊可以在佈局上的任何地方,而不是在球上。我曾經有這個工作,使用下面的代碼#1。但目前它已經破裂。當我點擊90度的球時,它會像點擊90 + x那樣點擊鼠標點擊一下。角度偏離了10度左右。Cocos2d:在鼠標點擊/觸摸方向上拍球

我使用levelhelper2工具集創建基本級別來佈置精靈。

/*--------------- 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);  
    } 

回答

0

你想要球持續飛翔或加速嗎? 恆速我會嘗試使用這樣的:

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

可選,您可以添加根據距離的持續時間。

我希望這會有所幫助。

+0

你可以用box2d來做這個嗎?我需要球從障礙物(牆壁)反彈等。謝謝 –

+0

我對box2d一無所知,但我認爲你只需要稍微改變一下代碼就可以從你的球到destX和destY做一個vec。 –

+0

我如何計算射擊球的力量/力量? – TomSawyer