0
votes

I'm using a sprite kit to create a game.

I have a player node which I control by touch but then I have an enemy node that moves on its own. I need the enemy to be able to shoot projectiles on its own. I'm guessing I would need a method for this and to call it. I need the direction of the projectiles to shoot wherever my player is. Any suggestions?

Here is the method I have:

  -(void)monstershoot
 {

SKSpriteNode * projectile = [SKSpriteNode spriteNodeWithImageNamed:@"projectile"];
projectile.position = _enemy.position;

CGPoint offset = rwSub(_player.position, projectile.position);

if (offset.x <= 0) return;

[_background addChild:projectile];

CGPoint direction = rwNormalize(offset);
CGPoint shootAmount = rwMult(direction, 1000);
CGPoint realDest = rwAdd(shootAmount, projectile.position);

// 9 - Create the actions
float velocity = 480.0/1.0;
float realMoveDuration = self.size.width / velocity;
SKAction * actionMove = [SKAction moveTo:realDest duration:realMoveDuration];
SKAction * actionMoveDone = [SKAction removeFromParent];
[projectile runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];
}

But nothing happens when I call it.

1
what does "nothing happens" mean?Cooper Buckingham
there are no projectiles being shot by the enemy. the enemy is just there. the point was for them to shoot at my player. but "nothing happens" @CHBuckinghamShariShar
NSLog offset, and you'll see why. :-)Cooper Buckingham

1 Answers

0
votes

It will do "nothing" in two cases: the image doesn't exist or the enemy is right of the player. Replace this line

if (offset.x <= 0) return;

by a check if the length of the offset vector is 0. You could write a method to calculate the length by using

sqrtf(powf(offset.x,2) + powf(offset.y,2))

Further you should use the length of shootAmount to calculate

float realMoveDuration = 1000 / velocity;

which will give you the same (and correct) speed for every projectile. But otherwise I see nothing wrong with your code.