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!
the
cos()andsin()functions both return a value from an input of radians. You want to useCC_RADIANS_TO_DEGREESto fix it.