Stefan Kendall
Stefan Kendall

Reputation: 67832

Stopping bounce when repeatedly jumping in spritekit

I have a player character and a ground tile. On both physics bodies, I have restitution set to 0.

To jump, I directly set the velocity.dy of the player. When the player comes back to the ground due to gravity, for the most part it works, or seems to.

Problems occur when I repeatedly jump. If I jump right as the player lands, there's some bounce and the height the player reaches on the next bounce doesn't always match the initial bounce.

I've tried various ways to force the velocity.dy to 0 when the user lands, but nothing fixes the weird jumping issue. How can I properly and smoothly have a consistent physics jump?

gif of issue

Upvotes: 2

Views: 801

Answers (1)

GeneCode
GeneCode

Reputation: 7588

Honestly, I am not sure what you are trying to accomplish. Normally we shouldn't mess with velocities of objects. In a typical Spritekit game, we must treat it like a "real world" situation and generally apply force or impulse on the object.

I suspect you are trying to make a Mario-like game. All you have to do is apply a big enough gravity to the physicsworld and apply impulse on the sprite to jump (on touchesBegan delegate).

Just now I went ahead and made a simple mario jump scenario in Spritekit. And this is what I ended up with by setting gravity -30 for the y-component and impulse y=100 on the mario sprite. (Frame rate is bad. Looks better on simulator/device)

enter image description here

PhysicsWorld setup:

[self.physicsWorld setGravity:CGVectorMake(0, -30)];
self.physicsWorld.contactDelegate = self;

Mario and platform sprite setup code:

SKSpriteNode *platform = [SKSpriteNode spriteNodeWithImageNamed:@"platform"];
platform.position = CGPointMake(view.frame.size.width/2.0,0);
platform.name = @"platform";
platform.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:platform.frame.size];
platform.physicsBody.categoryBitMask = platformCategory;
platform.physicsBody.dynamic = NO;
platform.physicsBody.usesPreciseCollisionDetection  = YES;
platform.physicsBody.affectedByGravity = NO;
[self addChild:platform];

SKSpriteNode *mario = [SKSpriteNode spriteNodeWithImageNamed:@"mario"];
mario.position = CGPointMake(view.frame.size.width/2.0, 400);
mario.name = @"mario";
mario.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:mario.frame.size];
mario.physicsBody.categoryBitMask = marioCategory;
mario.physicsBody.dynamic = YES;
mario.physicsBody.usesPreciseCollisionDetection  = YES;
mario.physicsBody.contactTestBitMask = platformCategory;
mario.physicsBody.affectedByGravity = YES;
[self addChild:mario];

touchesBegan:

SKSpriteNode *mario = (SKSpriteNode*)[self childNodeWithName:@"mario"];
[mario.physicsBody applyImpulse:CGVectorMake(0, 100)];

Upvotes: 2

Related Questions