Michael
Michael

Reputation: 123

SpriteKit ball loses all energy hitting wall, restitution=1

If I apply an impulse of 1 in the y direction, the ball bounces back and forth without losing any energy. However, if the initial impulse is 0.5 or below, the ball loses all energy instantly when it hits the wall. Why is this happening? I have a pretty good understanding of the properties of the SKPhysicsBody class. Try this code to see if you get the same behavior on your computer.

-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
    /* Setup your scene here */
    self.physicsWorld.gravity = CGVectorMake(0.0f, 0.0f);
    SKPhysicsBody* borderBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    self.physicsBody = borderBody;
    self.physicsBody.friction = 0.0f;
    self.backgroundColor = [SKColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.0];

    SKShapeNode *ball = [SKShapeNode node];
    CGMutablePathRef pathToDraw = CGPathCreateMutable();
    [ball setStrokeColor:[UIColor blackColor]];
    CGPathMoveToPoint(pathToDraw, NULL, 0, 0);
    CGPathAddEllipseInRect(pathToDraw, NULL, CGRectMake(-16, -16, 32, 32));
    ball.path = pathToDraw;

    ball.position = CGPointMake(size.width / 2, size.height / 2);
    ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:ball.frame.size.width/2];
    ball.physicsBody.friction = 0.0f;
    ball.physicsBody.restitution = 1.0f;
    ball.physicsBody.linearDamping = 0.0f;
    ball.physicsBody.allowsRotation = NO;

    [self addChild:ball];

    [ball.physicsBody applyImpulse:CGVectorMake(0, 0.5)];
}
return self;
}

Upvotes: 12

Views: 926

Answers (1)

Batalia
Batalia

Reputation: 2435

When the collision velocity is small enough (such as your CGVector of (0, 0.5)), Box2d underlying the Sprite Kit physics engine will compute the collision as inelastic (i.e. as if the restitution was 0, removing any bounciness), and the node will not bounce.

This is, per the Box2d documentation, to prevent jitter.

In the Box2d source code, you even have this line:

/// A velocity threshold for elastic collisions. Any collision with a relative linear
/// velocity below this threshold will be treated as inelastic.
#define b2_velocityThreshold            

Your impulse should be above this threshold for the restitution to be respected.

Upvotes: 4

Related Questions