问题:我希望气球在空中升起。它们可以相互碰撞,并且可以旋转。垂直方向的重力效果很好。

但是现在我想将一个篮子连接到每个气球上。这样做将导致篮子像气球一样“飞起来”。但是在现实生活中,篮子应该比气球“重”,因此它始终指向地面。

我将如何实现?

最佳答案

模拟带有篮筐的气球的一种方法是将重力设置为向下,以将篮筐拉向场景的底部,并对气球施加浮力以产生升力。这是如何执行此操作的示例:

定义常数

#define kRandMax        0x7fffffff
#define kNumBalloons    5


创建气球和篮子

self.physicsWorld.gravity = CGVectorMake(0, -3);

for (int i=0;i<kNumBalloons;i++) {

    // Create a balloon near the bottom of the scene with a random x position
    SKShapeNode *balloon = [SKShapeNode shapeNodeWithCircleOfRadius:16];
    balloon.fillColor = [SKColor redColor];
            balloon.name = @"balloon";
    balloon.physicsBody.allowsRotation = NO;
    CGFloat rand1 = arc4random_uniform(kRandMax) / (double)kRandMax;
    // A value in (-view.frame.size.width/2, view.frame.size.width/2)
    CGFloat xOffset = (rand1 - 0.5) *  view.frame.size.width / 2;
    balloon.position = CGPointMake (CGRectGetMidX(view.frame)+xOffset,
                                    CGRectGetMinY(view.frame)+50);
    balloon.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:16];
    [self addChild:balloon];

    // Create the basket
    SKSpriteNode *basket = [SKSpriteNode spriteNodeWithColor:[SKColor brownColor] size:CGSizeMake(8, 8)];
    basket.position = CGPointMake(balloon.position.x, balloon.position.y-24);
    basket.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:basket.size.width/2];
    [self addChild:basket];

    // Connect the balloon and basket with an SKPhysicsJointPin
    SKPhysicsJointPin *joint = [SKPhysicsJointPin jointWithBodyA:balloon.physicsBody
                                bodyB:basket.physicsBody anchor:balloon.position];
    [self.physicsWorld addJoint:joint];
}


在更新方法中,对每个气球施加力以产生升力

-(void)update:(CFTimeInterval)currentTime {
    // Apply buoyant force to all balloons in the scene
    [self enumerateChildNodesWithName:@"//balloon" usingBlock:^(SKNode *node, BOOL *stop){
        // Adjust force as needed
        [node.physicsBody applyForce:CGVectorMake(0, 17.2)];
    }];
}

关于objective-c - SpriteKit用关节在 body 上施加两个力,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27562083/

10-09 07:33