Pocketkid2
Pocketkid2

Reputation: 853

SpriteKit Two Objects bouncing.

So, I have a game in SpriteKit that involves to circular objects, and one is controlled by the player.

Problem:

When the player taps or drags along the screen, the first object is moved along with it. The second object is not controlled by the player or computer, but is to be a physics object that can be bounced around. However, Enabling the physics bodies only lets me push it around, but it won't bounce. I have set the restitution of both bodies to 1.0, and the friction to 0.0. There is no gravity. The way I am moving the player object is by calling the runAction on a move action when the player taps or drags, and that seems to let the second object be pushed around. I feel like I'm missing something, probably obvious.

Upvotes: 0

Views: 352

Answers (1)

ZeMoon
ZeMoon

Reputation: 20274

Using SKAction move will only make your node move to a specific point. If you want your player node to be moved in the direction of the touchPoint, then you need to use applyImpulse. Here's how you can achieve that:

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

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

Copy the rwAdd, rwSub, rwMult, rwLength and the rwNormalize methods from the tutorial.

Then, in your -touchesEnded method:

-(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 variable point to your desired node.

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

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

    // 5 - 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);

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

    //7 - Make the node ignore it's previous velocity (ignore if not required)
    projectile.physicsBody.velocity = CGVectorMake(0.0, 0.0);

    //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.

Upvotes: 1

Related Questions