Cocos2d iphone Cocos2d:按鼠标单击/触摸的方向射击球
在布局的左上角摆弄一个固定的球。当我使用鼠标点击时,我希望球被一个力击中并通过鼠标点击。鼠标单击可以位于布局上除球之外的任何位置。我曾经使用下面代码中的1使它工作。但它现在坏了。当我以90度的角度点击球时,它会离鼠标点击稍微远一点,比如说90+x。角度偏离了10度左右 我使用levelhelper2工具集创建了基本标高来布局精灵Cocos2d iphone Cocos2d:按鼠标单击/触摸的方向射击球,cocos2d-iphone,2d,box2d,Cocos2d Iphone,2d,Box2d,在布局的左上角摆弄一个固定的球。当我使用鼠标点击时,我希望球被一个力击中并通过鼠标点击。鼠标单击可以位于布局上除球之外的任何位置。我曾经使用下面代码中的1使它工作。但它现在坏了。当我以90度的角度点击球时,它会离鼠标点击稍微远一点,比如说90+x。角度偏离了10度左右 我使用levelhelper2工具集创建了基本标高来布局精灵 /*--------------- touchEnded ------------------------------------*/ -(void)t
/*--------------- 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);
}
你想让球一直飞还是加速? 对于恒定速度,我会尝试使用以下内容:
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));
可选您可以根据距离添加持续时间
我希望这能有所帮助。您可以使用box2d来完成此操作吗。我需要球从障碍物、墙壁等处反弹。。谢谢我对box2d一无所知,但我想你只需要稍微修改一下代码,就可以将球的vec设置为destX和destY。我如何计算射门的力量?