Question

I have made this sprite that i can grab and move around. My issue is that i want to be able to "throw" the sprite. Meaning, when i release the sprite i want it to continue in the direction that i moved it. Just like throwing a ball.

What should i do?

@implementation NPMyScene
{
    SKSpriteNode *sprite;
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
        sprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:sprite.size.width/2];

        sprite.physicsBody.dynamic = YES;
        self.scaleMode = SKSceneScaleModeAspectFit;

        sprite = [SKSpriteNode spriteNodeWithImageNamed:@"GreenBall"];
        sprite.position = CGPointMake(CGRectGetMidX(self.frame),
                                      CGRectGetMidY(self.frame));

        sprite.physicsBody.velocity = self.physicsBody.velocity;
        sprite.physicsBody.affectedByGravity = false;
        sprite.physicsBody.dynamic = true;
        sprite.physicsBody.friction = 0;
        [sprite.physicsBody isDynamic];

        [sprite.physicsBody allowsRotation];

        [self addChild:sprite];
    }
    return self;
}



-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 [self touchesMoved:touches withEvent:event];
}



-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
   [sprite runAction:[SKAction moveTo:[[touches anyObject] locationInNode:self]duration:0.21]];
}
Was it helpful?

Solution

If you are talking about applying physics to the ball, then you need to think deeper about how Sprite Kit deals with physics.

When you specify the 'moveTo' action, you're not actually using Sprite kit's physics engine at all. You're simply specifying a point to animate that sprite to.

What you should be doing to achieve the effect you're looking for is attaching the sprite's position to your finger as it's moved around on the screen like so:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
   sprite.position = [[touches anyObject] locationInNode:self];
}

Then when the finger is lifted, you need to calculate the direction and speed in which your finger just moved and apply the appropriate amount of force to the sprite's physics body using the applyForce method:

[sprite.physicsBody applyForce:calculatedForce];

You will need to figure out how to calculate the force to be applied, but play around with the applyForce method and look at what information you are able to get back from the touchedMoved: event to help you apply that force. Hope that helps.

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