SpriteKit ball loses all energy hitting wall, restitution=1

◇◆丶佛笑我妖孽 提交于 2019-12-22 03:40:16

问题


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;
}

回答1:


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.



来源:https://stackoverflow.com/questions/22058292/spritekit-ball-loses-all-energy-hitting-wall-restitution-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!