ios - Sprite Kit 销接头似乎有一个不正确的 anchor

标签 ios objective-c sprite-kit

我正在使用 Sprite Kit 测试针接头,我发现发生了一些不寻常的事情。

我想要的设置是这样的:一个宽的扁平盒子和两个圆圈;圆圈通过 SKPhysicsPinJoints 连接到盒子,因此它们可以充当轮子。

这是我的代码。我尽量让它简洁:

- (SKNode*) createWheelWithRadius:(float)wheelRadius {
    CGRect wheelRect = CGRectMake(-wheelRadius, -wheelRadius, wheelRadius*2, wheelRadius*2);

    SKShapeNode* wheelNode = [[SKShapeNode alloc] init];
    wheelNode.path = [UIBezierPath bezierPathWithOvalInRect:wheelRect].CGPath;

    wheelNode.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:wheelRadius];

    return wheelNode;
}


- (void) createCar {

    // Create the car
    SKSpriteNode* carNode = [SKSpriteNode spriteNodeWithColor:[SKColor yellowColor] size:CGSizeMake(150, 50)];
    carNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carNode.size];
    carNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    [self addChild:carNode];

    // Create the left wheel
    SKNode* leftWheelNode = [self createWheelWithRadius:30];
    leftWheelNode.position = CGPointMake(carNode.position.x-80, carNode.position.y);
    [self addChild:leftWheelNode];

    // Create the right wheel
    SKNode* rightWheelNode = [self createWheelWithRadius:30];
    rightWheelNode.position = CGPointMake(carNode.position.x+80, carNode.position.y);
    [self addChild:rightWheelNode];

    // Attach the wheels to the body
    CGPoint leftWheelPosition = leftWheelNode.position;
    CGPoint rightWheelPosition = rightWheelNode.position;

    SKPhysicsJointPin* leftPinJoint = [SKPhysicsJointPin jointWithBodyA:carNode.physicsBody bodyB:leftWheelNode.physicsBody anchor:leftWheelPosition];
    SKPhysicsJointPin* rightPinJoint = [SKPhysicsJointPin jointWithBodyA:carNode.physicsBody bodyB:rightWheelNode.physicsBody anchor:rightWheelPosition];

    [self.physicsWorld addJoint:leftPinJoint];
    [self.physicsWorld addJoint:rightPinJoint];
}

我期望的是销接头固定在它们的中心点;然而,当我对此进行测试时,关节的 anchor 似乎离得很远。

我是否漏掉了一些非常明显的东西?

最佳答案

我也有这个问题,原因是在设置 Sprite 位置之前设置物理体。

carNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carNode.size];
carNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));

将上面的改成

carNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
carNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:carNode.size];

它应该可以工作。谢谢斯米克。

SpriteKit: How to create Basic Physics Joints

关于ios - Sprite Kit 销接头似乎有一个不正确的 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342417/

相关文章:

ios - TeeChart 底轴标签在 iOS 中被截断

ios - UIWebView吸引用户点击链接

objective-c - 当属性存在时,ivar 的目的是什么?

swift - 从文件名加载 SpriteKit 关卡

swift - 有什么方法可以在 swift/SpriteKit 中从父项中删除单个/特定子项?

swift - 如何在保持重力的同时保持 spritekit 节点中的能量恒定

ios - Swift - 在 UIScrollView 中设置背景图像的问题

ios - 如何为闭包分配内存及其存储机制是什么?

iphone - 如何在 GridView 中添加/删除行

c++ - cvExtractSURF 抛出异常,cvCreateSeq 中输入数组 ( ) 的大小不正确