在布局的左上角玩一个球(静止)。当我使用鼠标点击时,我希望球被力击中并通过鼠标点击。鼠标单击可以是布局上的任何位置,而不是球。我曾经使用过以下代码中的#1。但它此刻破了。当我点击90度的球时,它会像点击90 + x一样远离鼠标点击。角度偏离10度左右。
我使用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 :(得分: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));
可选您可以根据距离添加持续时间。
我希望这会有所帮助。