Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Sprite Kit, how can I let an object jump?

I am making a game with sprite kit and now I am wondering what the best way is to let the object 'jump'. So it will be launched up vertical with a few pixels. This is the code of the object I want to jump:

SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"bal.png"];
sprite.position = CGPointMake(self.frame.size.width/4 + arc4random() % ((int)self.frame.size.width/2), (self.frame.size.height/2 + arc4random() % ((int)self.frame.size.height/2)));
sprite.color = [self randomColor];
sprite.colorBlendFactor = 1.0;
sprite.xScale = 0.2;
sprite.yScale = 0.2;
[self addChild:sprite];
sprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:sprite.size.width/2];
self.physicsWorld.gravity = CGVectorMake(0.0f, -4.0f);
like image 844
Vince Avatar asked Dec 20 '22 23:12

Vince


1 Answers

I would try to avoid setting object's velocity directly. Instead I'd apply forces and impulses to the objects. For most cases this works better as it doesn't break the physics simulation. For example this is how I'd make my object jump:

- (void) jump:(SKSpriteNode*)obj
{
    if (obj.isTouchingGround)
    {
        CGFloat impulseX = 0.0f;
        CGFloat impulseY = 25.0f;           
        [object.physicsBody applyImpulse:CGVectorMake(impulseX, impulseY) atPoint:obj.position];   
    }
}
like image 200
JKallio Avatar answered Dec 27 '22 11:12

JKallio