4

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);
CubeJockey
  • 2,209
  • 8
  • 24
  • 31
Vince
  • 648
  • 1
  • 7
  • 17

2 Answers2

7

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];   
    }
}
JKallio
  • 903
  • 5
  • 15
4

Give a velocity to the body by changing the velocity property of the physicsBody associated with the sprite.

Specifically, you need to add

sprite.physicsBody.velocity = CGVectorMake(vx,vy);

EDIT : If you want to to do this through actions, make use of one of these two class methods of SKAction

+ (SKAction *)followPath:(CGPathRef)path duration:(NSTimeInterval)sec;
+ (SKAction *)moveByX:(CGFloat)deltaX y:(CGFloat)deltaY duration:(NSTimeInterval)sec;

However, using any of these requires you to calculate stuff based on your velocity vector and take care of gravity yourself(for giving suitable deltaX and deltaY or the correct path) which is quite unnecessary. Why not just mention velocity and let SpriteKit work it out for you?

Roshan
  • 1,937
  • 1
  • 13
  • 25