如何修复游戏中的物体轨迹?

时间:2011-07-19 18:53:17

标签: iphone objective-c cocoa-touch cocos2d-iphone

我正在用操纵杆制作iPhone游戏。它有一艘应该在操纵杆轨道上发射子弹的船,但由于某种原因,我不能让子弹向正确的方向移动。有人可以帮我弄清楚我可能做错了什么吗?

这是我的代码:

-(void) shootBulletFromShip:(Ship*)ship
{
    double degrees = [[[NSUserDefaults standardUserDefaults] objectForKey:@"lol"] doubleValue];    
    NSLog(@"%f",degrees);

    float fDegrees = degrees;

    velocity = CGPointMake(1, fDegrees);


    outsideScreen = [[CCDirector sharedDirector] winSize].width;

    self.position = CGPointMake(ship.position.x,ship.position.y);
    self.visible = YES;

    [self scheduleUpdate];
}

2 个答案:

答案 0 :(得分:1)

我认为您在下一行中错误地设置了子弹的速度。

velocity = CGPointMake(1, spread);

如果spread指示一个角度,您应该将该角度的正弦和余弦作为CGPoint的x和y分量传递,如下所示。

velocity = CGPointMake(cos(spread), sin(spread));

您可能需要稍微修改一下,具体取决于您的角度是以弧度还是以度数表示。

答案 1 :(得分:0)

// Calculate the angle of the touch from the center of the joypad
float dx = (float)joypadBG.position.x - (float)convertedPoint.x;
float dy = (float)joypadBG.position.y - (float)convertedPoint.y;

float distance = sqrtf((joypadBG.position.x - convertedPoint.x) * (joypadBG.position.x - convertedPoint.x) + (joypadBG.position.y - convertedPoint.y) * (joypadBG.position.y - convertedPoint.y));

// Calculate the angle of the players touch from the center of the joypad
float touchAngle = atan2(dy, dx);

// If the players finger is outside of the joypad, make sure the joypad cap is drawn at the // joypad edge.
if (distance > joypadMaxRadius) 
{
    [joystick setPosition:ccp(joypadBG.position.x - cosf(touchAngle) * joypadMaxRadius, joypadBG.position.y - sinf(touchAngle) * joypadMaxRadius)];
} 
else 
{
    [joystick setPosition:convertedPoint];
}

diff = ccpSub([joystick position], joypadBG.position);
float angleRadians = atanf((float)diff.y / (float)diff.x);

float angleOffset = CC_DEGREES_TO_RADIANS(90);

if(diff.x < 0)
{
    angleRadians += angleOffset;
}
else
{
    angleRadians -= angleOffset;
}