Hunter23
Hunter23

Reputation: 69

Sprite Kit. Follow Node Position (Objective C)

Is there a way for a sprite node to follow another sprite node with an SKAction? i am using this but it doesn't seem to fully catch up with my rocket.

move = [SKAction moveTo:_rocket.position duration:1.0];
[beams runAction:move];

I have a rocket firing a laser beam at another rocket, and i want the beam to follow the rocket when it fires, but also slowly catch up to it so it hits it. The code above does follow it but stays slightly behind it.

Here is the code for my two movements for the rockets

SKAction *moveRight = [SKAction moveByX: 100.0 y:0 duration:2];
SKAction *sequence = [SKAction sequence:@[moveRight]];
SKAction *endless = [SKAction repeatActionForever:sequence];
[spaceShip runAction:endless withKey:@"rocketKey"];


Second Rocket 
SKAction *moveShip = [SKAction moveByX:150.0f y:0 duration:2.00f];
SKAction *sequence = [SKAction sequence:@[moveShip]];
SKAction *repeat = [SKAction repeatActionForever:sequence];

[spaceShipL runAction:repeat];

I've tested it without the SKAction and it would work fine but i need both of the rockets to be always moving.

Upvotes: 1

Views: 239

Answers (1)

Beau Nouvelle
Beau Nouvelle

Reputation: 7252

There's a few ways to achieve this that I know of.

  1. You could use some kind of pathfinding.

  2. You could add your laser beam as a child to rocket2, and move it relative to that rocket. (You would need some extra calculations to ensure that if rocket2 should move towards the laser, the laser won't slow down/move backwards)

  3. Best solution, regularly get the position of rocket2 and have the laser follow it. Rather than using moveTo, use applyForce. This won't be bound by time, and so should be able to catch up to your rocket:

    SKSpriteNode *laser = [SKSpriteNode spriteNodeWithImageNamed:@"laser"];
    laser.physicsBody = [SKPhysicsBody bodyWithTexture: laser.texture size: laser.texture.size];
    
    static const CGFloat thrust = 0.10;
    CGVector thrustVector = CGVectorMake(thrust*cosf(laserDirection),
                               thrust*sinf(laserDirection));
    [laser.physicsBody applyForce:thrustVector];
    

Upvotes: 1

Related Questions