Question

I'm kind of a newb in SpriteKit, game dev, as a matter of fact I'm just learning. So I got to a point where I what to move a bunch of nodes towards a users tap location. So far I fought that I might calculate a virtual right triangle and get sin and cos of angles based on the sides. Unfortunately that left me with a very strong impulse that doesn't really consider the user tap location.

Any ideas?

Thanks in advance.

Was it helpful?

Solution

Look up the shooting projectiles section in the tutorial by Ray Wenderlich here:

http://www.raywenderlich.com/42699/spritekit-tutorial-for-beginners

Change the code from the tutorial as follows:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    // 1 - Choose one of the touches to work with
    UITouch * touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    // 2 - Set up initial location of projectile
    SKSpriteNode * projectile = [self childNodeWithName:@"desirednode"];
    //make projectile point to your desired node.

    // 3- Determine offset of location to projectile
    CGPoint offset = rwSub(location, projectile.position);

    // 4 - Bail out if you are shooting down or backwards. You can ignore this if required.
    if (offset.x <= 0) return;

    // 5 - OK to add now - we've double checked position
    [self addChild:projectile];

    // 6 - Get the direction of where to shoot
    CGPoint direction = rwNormalize(offset);

    // 7 - Make it shoot far enough to be guaranteed off screen
    float forceValue = 200; //Edit this value to get the desired force.
    CGPoint shootAmount = rwMult(direction, forceValue);

    //8 - Convert the point to a vector
    CGVector impulseVector = CGVectorMake(shootAmount.x, shootAmount.y);
    //This vector is the impulse you are looking for.

    //9 - Apply impulse to node.
    [projectile.physicsBody applyImpulse:impulseVector];

}

The projectile object in the code represents your node. Also, you will need to edit the forceValue to get the desired impulse.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top