0
votes

I'm using cocos2d to make a game and I'm trying to create a shot path from the current enemy position on the enemies angle at a certain length.

Here is the code I am using to rotate and shoot the gun.

gun runAction: [CCSequence actions: [CCDelayTime actionWithDuration:2.0],
                 [CCCallBlockN actionWithBlock:^(CCNode *node)
                  { [self shootEnemyLaserFromPositionAtAngle:gun];}],
                 [CCRotateTo actionWithDuration:0.5 angle:250],
                 [CCCallBlockN actionWithBlock:^(CCNode *node)
                  { [self shootEnemyLaserFromPositionAtAngle:gun];}],
                 [CCRotateTo actionWithDuration:0.5 angle:230],
                 [CCCallBlockN actionWithBlock:^(CCNode *node)

I am using this equation to calculate the vector (this code is in shootEnemyLaserFromPositionAtAngle):

CGPoint endPoint = CGPointMake(gun.position.x + (800 * cos(gun.rotation)), gun.position.y + (800 * sin(gun.rotation)));
NSLog(@"end Point x: %f, %f", endPoint.x, endPoint.y);

shipLaser.position = gun.position;

CGPoint shootVector = ccpNormalize(ccpSub(endPoint, shipLaser.position));
CGPoint shootTarget = ccpMult(shootVector, _winSize.width*2);

[shipLaser runAction:[CCSequence actions: [CCMoveBy actionWithDuration:4.0 position:shootTarget],
                      [CCCallFuncN actionWithTarget:self selector:@selector(invisNode:)], nil]];

My problem is that it ends up shooting off in weird directions. My endPoint values are printed out as so. I have also printed out the angle of the gun rotation below:

angle: -90.000000
end Point x: 21.541107, -499.593536
angle: -110.000000
end Point x: -419.216644, 250.997940
angle: -130.000000
end Point x: 86.166939, 959.688538

I notice the angle is suddenly negative. I tried changing to positive angles (adding 360 to the negative angle), but that resulted in the same end points.

Can anyone help or give me some things to try??

Thanks!

2

2 Answers

2
votes

the cos() and sin() functions both return a value from an input of radians. You want to use CC_RADIANS_TO_DEGREES to fix it.

1
votes

You need to convert gun.rotation from degrees to radians if trying to find its sine or cosine. Use float gunRotation = CC_DEGREES_TO_RADIANS(gun.rotation); (or double) and pass that in to the trigonometric functions. Of course there may be other problems lurking outside of those fragments, so do update the question if you find other related issues.