ios - 如何防止 SKSpriteNode 的子节点与其父节点一起旋转?

标签 ios rotation sprite-kit skphysicsbody

我正在使用 SpriteKit 编写一个 iOS 游戏,其中包含许多带标签的球。我通过构建一个带有 2 个子节点的父 SKSpriteNode 来构建这些“rollingBalls”:

a) 一个 SKShapeNode(实际的圆形)

b) 和一个 SKLabelNode(标签)

球将在整个屏幕上移动,在二维空间中与彼此和其他物体相互作用,并且完全取决于预期的物理特性(想想台球)。但如果可能的话,我希望标签不随父级一起旋转,以便始终保持易于阅读。

最简单的方法是什么?

标签不应该是容器的子元素吗?还有其他方法可以将它与 ballShape Hook 吗?或者我可以在标签上设置一些属性等吗?

这是我现在得到的:

double ballDiameter = 40;
UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: 
                            CGRectMake(-ballDiameter / 2, -ballDiameter / 2, 
                                        ballDiameter, ballDiameter)];

SKSpriteNode *container = [[SKSpriteNode alloc]init];

container.name = @"rollingBall";

SKShapeNode *ballShape = [[SKShapeNode alloc] init];
ballShape.path = ovalPath.CGPath;

SKLabelNode *ballLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial"];
ballLabel.text = @"some random string";
ballLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter;
ballLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
ballLabel.position = CGPointMake(0,0);

[container addChild:ballShape];
[container addChild:ballLabel];

container.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:ballDiameter / 2];
container.physicsBody.usesPreciseCollisionDetection = YES;

最佳答案

enter image description here

将所有标签放在一个容器中,将标签添加到关联节点的用户数据中,然后更新标签位置。

// Add a container as a scene instance variable.
SKNode *labels;

- (void)addLabelContainer
{
    labels = [SKNode node];
    [self addChild:labels];
}

- (void)addLabelForNode:(SKNode*)node
{
    SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
    node.userData = [NSMutableDictionary dictionaryWithObject:label forKey:@"label"];
    label.text = node.name;
    label.fontSize = 5;
    label.zPosition = node.zPosition + 1;
    [labels addChild:label];
}

- (void)removeLabelForNode:(SKNode*)node
{
    [[node.userData objectForKey:@"label"] removeFromParent];
    [node.userData removeObjectForKey:@"label"];
}

- (void)update:(NSTimeInterval)currentTime
{
    for (SKNode *node in self.children) {
        SKNode *label = (SKLabelNode*)[node.userData objectForKey:@"label"];
        if (label) {
            label.position = node.position;
        }
    }
}

参见 https://github.com/pmark/MartianRover/blob/master/hiSpeed/hiSpeed/Scenes/LimboScene.m

关于ios - 如何防止 SKSpriteNode 的子节点与其父节点一起旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414213/

相关文章:

ios - 在 Spritekit 的 SKShapeNode 中将特定点居中

ios - 我如何在 GameplayKit/SpriteKit 中以有效的方式对实体和组件进行建模

sprite-kit - 在 Sprite Kit 中将数据存储在 plist 中与在场景编辑器中设置数据有什么区别?

ios - 无法让 UIScrollView 进行缩放和滚动

ios - 'NSInvalidArgumentException'

ios - indexPath.row 在 tableView 自定义单元格 iOS 中没有给出正确的值

javascript - 如何让齿轮在单击按钮时旋转,然后在单击设置次数后接受?

c++ - 围绕一个公共(public)点旋转四条线

ios - 将 Node 放置在 ARKit World 中的触摸位置

javascript - Google map 折线上的符号始终旋转