SpriteKit - 在关节之间绘制动态线

Aug*_*ust 2 ios sprite-kit

我正在尝试使用 iOS SpriteKit 使用内置物理以编程方式构建一个钟摆。

目前,我有摆枢轴、重物和允许重物摆动的有限关节...但是,我不知道如何在枢轴和重物之间编写一条线(杆)。

我认为用 SKShapeNode 画一条线将是一个开始......?

-(void)setupPendulum
{
    pivot = [SKSpriteNode spriteNodeWithImageNamed:@"pivot.png"];
    pivot.position = CGPointMake(self.size.width / 2, self.size.height / 2);
    pivot.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:1.0];
    pivot.physicsBody.dynamic = NO;
    pivot.physicsBody.affectedByGravity = NO;
    pivot.xScale = 0.25;
    pivot.yScale = 0.25;
    [self addChild:pivot];

    weight = [SKSpriteNode spriteNodeWithImageNamed:@"weight.png"];
    weight.position = CGPointMake(150, 512);
    weight.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:100.0];
    weight.physicsBody.dynamic = YES;
    weight.physicsBody.affectedByGravity = YES;
    weight.physicsBody.mass = 0.5;
    weight.xScale = 0.75;
    weight.yScale = 0.75;
    [self addChild:weight];

    SKPhysicsBody *ab = pivot.physicsBody;
    SKPhysicsBody *bb = weight.physicsBody;
    CGPoint ap = pivot.position;
    CGPoint bp = weight.position;
    SKPhysicsJointLimit *joints = [SKPhysicsJointLimit jointWithBodyA:ab
                                                                bodyB:bb
                                                              anchorA:ap
                                                              anchorB:bp];
    [self.physicsWorld addJoint:joints];
}
Run Code Online (Sandbox Code Playgroud)

小智 5

我的项目需要而SKPhysicsJointLimit不是引脚,因此经过大量试验和错误后,我找到了以下解决方案。该线被移除并绘制在 中didSimulatePhysics。当“卫星船”围绕“母船”运行时,该线将其连接起来。我对这一切都很陌生,所以我很感激任何关于这种方法的反馈。

首先设置变量:

SKShapeNode *_lineNode;
Run Code Online (Sandbox Code Playgroud)

现在在 didSimulatePhysics 中画一条线:

- (void)didSimulatePhysics {
    if (_lineNode){
        [_lineNode removeFromParent];
    }
    SKNode *satelliteShip = [self childNodeWithName:kSatelliteShipName];
    CGMutablePathRef pathToDraw;
    pathToDraw = CGPathCreateMutable();
    CGPathMoveToPoint(pathToDraw, NULL, motherShip.position.x, motherShip.position.y);
    CGPathAddLineToPoint(pathToDraw, NULL, satelliteShip.position.x, satelliteShip.position.y);
    CGPathCloseSubpath(pathToDraw);

    _lineNode = [SKShapeNode node];
    _lineNode.path = pathToDraw;
    CGPathRelease(pathToDraw);
    _lineNode.strokeColor = [SKColor grayColor];
    [self addChild:_lineNode];
}
Run Code Online (Sandbox Code Playgroud)