使用Cocos2d找到矢量角度

时间:2012-01-12 04:57:50

标签: iphone cocos2d-iphone

我找不到问题所在。我使用ccpToAngle()来找到矢量的角度,但无法获得适当的角度。我的球被发射/初始位置在cpp(170,40)并使用滑动我想扔它  我写了一个角度,

 -(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {

    CGPoint location = [touch locationInView: [touch view]];
    CGPoint vector = ccpSub(location, ccp(170 ,40));
    normalVector = ccpNormalize(vector);
    float angleRads = ccpToAngle(normalVector);
    float angle = CC_RADIANS_TO_DEGREES(angleRads);
   }

但是如果我刷了更多,那么角度会增加。我认为,每次在相同的线/方向上滑动角度应该相同。但是在这里,我只能获得70到90度之间的角度,如果滑动更多则角度接近60,66度。

我想要0到180度之间的角度。它是否有可能将ccp(170,40)视为轴起点&在Cocos2d中找到向量的角度?

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果你想找到一个滑动角度,你必须在这里使用三角法。

这里有一些可以帮到你......

- ( void ) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
   locationTouchBegan = [touch locationInView: [touch view]];
    //location is The Point Where The User Touched
    locationTouchBegan = [[CCDirector sharedDirector] convertToGL:locationTouchBegan];
    //Detect the Touch On Ball
    if(CGRectContainsPoint([ball boundingBox], locationTouchBegan))
    {
        isBallTouched=YES;
    } 

}

这是你如何检测到球被触摸

现在触摸结束我们可以计算方向。

- ( void ) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
   locationTouchEnded = [touch locationInView: [touch view]];
    locationTouchEnded = [[CCDirector sharedDirector] convertToGL:locationTouchEnded];
    [self calculateDirections];
}

这就是我们计算方向的方式。

-(void)calculateDirections
{
    if (isBallTouched==YES )
    {
        perpendicularBig = screenSize.height - ball.position.x;
        baseSmall = screenSize.width/2 - locationTouchEnded.x; // if the ball is at center.
        perpendicularSmall=locationTouchEnded.y - ball.position.x;
        baseBig=(perpendicularBig*baseSmall)/perpendicularSmall;
        endPoint=ccp(screenSize.width/2 - baseBig,320); //320 can replace by the value of end point y where you want to end the ball run. 
        [self moveBall:3.0f];
    }
}
-(void)moveBall:(float)duration
{

    [ball runAction:[CCJumpTo actionWithDuration:duration position:ccp(endPoint.x,endPoint.y) height:20 jumps:1]];
    isBallTouched = NO;
}