I'm new to cocos2d and game developing. Currently I'm following this tutorial and, so far so good, basically:
- Monsters spawn off screen and move from right to left and out of screen again.
- The player is in a set position and can't move.
- The player shoot ninja stars on touch.(still no collision)
The problem: Projectile speed changes (faster the closer i touch the upper or lower border of the screen (game is played horizontally positioned as shown in the image below the code). I belive that's because the target point gets farthest as I touch closer to my character and the upper/lower edges, and the star needs to get to that point in a given time (see the code). I would like the speed to be constant, no matter where I touch. How can I achieve that?. I'm sorry if I'm messy on my explanation.
This is the star/projectile code:
- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
// 1
CGPoint touchLocation = [touch locationInNode:self];
// 2
CGPoint offset = ccpSub(touchLocation, _player.position);
float ratio = offset.y/offset.x;
int targetX = _player.contentSize.width/2 + self.contentSize.width;
int targetY = (targetX*ratio) + _player.position.y;
CGPoint targetPosition = ccp(targetX,targetY);
// 3
CCSprite *projectile = [CCSprite spriteWithImageNamed:@"projectile.png"];
projectile.position = _player.position;
[self addChild:projectile ];
// 4
CCActionRotateBy *actionRotate = [CCActionRotateBy actionWithDuration: 0.5f angle:360];
[projectile runAction:[CCActionRepeatForever actionWithAction:actionRotate]];
CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration: 1.5f position:targetPosition];
CCActionRemove *actionRemove = [CCActionRemove action];
[projectile runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove]]];
}
As you can see in the actionMove line, projectile speed depends on the time it takes to reach the targetPosition (this image may help [not enough reputation to post images]): http://cdn5.raywenderlich.com/wp-content/uploads/2014/01/Cocos2D_MonsterMath.png
Thanks in advance, any help or reading material is appreciated.