【问题标题】:Find an angle of vector using Cocos2d使用 Cocos2d 求矢量的角度
【发布时间】:2012-01-12 04:57:50
【问题描述】:

我没有找到问题所在。我正在使用 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 中找到向量的角度?

提前致谢。

【问题讨论】:

  • 我建议你自己使用数学库来做这件事。这是非常简单但有价值的知识。只需在线查找一个简单的三角函数教程。
  • 在您的代码中插入NSLogNSLog (@"location: %.0fx%.0f vector: %.0fx%.0f angle: %.0f", location.x, location.y, vector.x, vector.y, angle);。然后用手指在你的 170x40 周围画一个圆圈,你就会看到问题到底出在哪里。

标签: iphone cocos2d-iphone


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多