【问题标题】:SKLabelNode Not Showing [SpriteKit]SKLabelNode 不显示 [SpriteKit]
【发布时间】:2016-07-27 00:36:41
【问题描述】:

我创建了一个名为 smallScreen 的 SKShapeNode 和一个名为 screenLabel 的 SKLabelNode。

我后来尝试在 smallScreen 中显示 screenLabel。但是,当我运行代码时,它不起作用。我尝试将 screenLabel 作为孩子添加到 self,这似乎允许显示文本。每当我将 screenLabel 作为子节点添加到 smallScreen 时,它都不会显示。请帮忙,非常感谢。

    self.smallScreen = (self.childNodeWithName("screen") as? SKShapeNode)!
    self.smallScreen.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height * 2/3)

    screenLabel.text = "Screen"
    screenLabel.fontSize = 30
    screenLabel.fontColor = UIColor.redColor()
    screenLabel.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height * 2/3)
    screenLabel.hidden = false
    self.smallScreen.addChild(screenLabel)

【问题讨论】:

  • 如果您的问题已解决,请将问题标记为已解决,谢谢。

标签: swift xcode sprite-kit


【解决方案1】:

默认情况下,在 Sprite-kit 中,场景的原点放置在视图的左下角。它的默认值是CGPointZero,你不能改变它。 (source)。

精灵的 (SKSpriteNode) 锚点默认为 (0.5,0.5),对应于帧的中心 (source)。

SKShapeNode 没有锚点

LearnCocos2D 回答了这个问题:

当您使用图像时,您可能需要将其与其节点的位置对齐。 除了通过anchorPoint之外别无他法,因为 图像本身无法修改(无论如何都不容易)。

创建形状时,您可以完全控制形状的对齐方式 通过CGPath的形状。您可以简单地将路径转换为更改 形状相对于节点位置的对齐方式。

这是我的解释,不是事实。

那么,你的代码发生了什么

我不知道你是如何初始化你的形状的,我只是举个例子:

/* Create a Shape Node representing a rect centered at the Node's origin. */
    @available(iOS 8.0, *)
    public convenience init(rectOfSize size: CGSize)

所以我们创建这样的形状:

self.smallScreen = SKShapeNode.init(rectOfSize: CGSizeMake(200,200))

首先,将SKShapeNode 放在屏幕的 X 中心作为 X 坐标,Y = self.frame.size.height * 2/3。事实上,您的smallScreen 是可见的。

说到你的标签,你已经把它添加到smallScreen,所以screenLabel必须尊重他父母的对齐方式。 事实上,您只需进行此更改即可查看您的标签:

发件人:

   screenLabel.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height * 2/3)

收件人:

screenLabel.position = CGPointZero

并且您的标签根据其父级的对齐方式定位到smallScreen 的中心。

【讨论】:

  • In Sprite-kit by default, a scene’s origin is placed in the lower-left corner of the view. Its default value is CGPointZero and you can’t change it. (source). 不知道你的意思是什么?您可以更改场景的锚点,使 (0,0) 成为中心。
  • 啊,你的意思是说它的默认位置为零并且不能改变,这是有道理的,因为场景不应该有位置
  • 感谢您的宝贵时间!事实证明,smallScreen 中心的坐标是 (0,0),我猜它与 self 的坐标系不同,因为我将 screenLabel 添加到 smallScreen 而不是 self。该代码现在对我有用。耶!
  • @Jack 你什么意思?显然你需要一个 CGPoint,CGPointZero 也是一个 CGPoint。
  • @AlessandroOrnano 抱歉,没有深入阅读您的答案,只是略读。是的,你完全正确。 :)
猜你喜欢
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多