ios - 如何改变SpriteKit的坐标系

标签 ios swift sprite-kit

所有SKSpriteNode都有它们的起源,也称为anchorPoint,如果我没记错的话,就在它们的中间。我想将该原点翻译为位于节点顶线的中间。我在 init() 方法中尝试了以下方法,但它不起作用:

self.anchorPoint = self.anchorPoint.applying(
    CGAffineTransform.init(translationX: 0, y: self.frame.size.height/2)
)

PS:我用它来简化以下内容: 我创建了一个 SpriteNode 数组,它们都位于新的 CGPoint.zero 位置,然后,我必须将其应用于它们:

for i in 0..<arr.count {
    arr[i].position.y += self.size.height*CGFloat((i+1)/(arr.count+1))
}

这是代码:

import SpriteKit

class SKLayer: SKSpriteNode {

init(inside scene: SKScene, withLabels texts: [String]) {
    super.init(texture: nil, color: .clear, size: scene.size)

    self.anchorPoint = CGPoint(x: 0.5, y: 1)
    converted(texts).forEach(self.addChild(_:))

    self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    self.position = .zero
}

private func converted(_ text: [String]) -> [SKNode] {

    var arr = [SKLabelNode]()

    text.forEach {
        arr.append(SKLabelNode(text: $0))
    }

    for i in 0..<arr.count {
        arr[i].position.y = CGFloat(i) * arr[0].frame.height
    }

    return arr
}

required init?(coder aDecoder: NSCoder) {
    fatalError()
}

}

class GameScene: SKScene {

override func didMove(to view: SKView) {
    self.addChild(
        SKLayer(inside: self, withLabels: ["Welcome", "Hello", "Bye", "Help"])
    )
}

}

这是代码编译后的结果的图片: ScreenShot

我希望节点从上到下,而不是相反。哎哟,我想看到顶部的“欢迎”标签,然后是“texT”标签,然后是其他标签。

最佳答案

根据docs ,

这就是 anchor 的工作原理:

Anchor points are specified in the unit coordinate system, shown in the following illustration. The unit coordinate system places the origin at the bottom left corner of the frame and (1,1) at the top right corner of the frame. A sprite’s anchor point defaults to (0.5,0.5), which corresponds to the center of the frame.

enter image description here

从这张图中我们可以看到,要将 anchor 设置为上边框的中间,需要将其设置为(0.5, 1)

您尝试将 anchor 转换为 self.frame.size/2 这可能是一个大于 1 的数字。嗯,根据文档,(0, 0) - (1, 1) 覆盖 Sprite 节点的整个框架。如果将其设置为大于 (1, 1) 的值,则 anchor 将位于节点框架之外。

关于ios - 如何改变SpriteKit的坐标系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032784/

相关文章:

swift - 快节奏的 SpriteKit 游戏具有不规则的 CPU 事件,并且尽管帧速率保持在高水平,但仍会出现抖动/滞后 - Swift

ios - SKSpriteNode - 如何写入构成 Sprite 图像的像素?

ios - Swift 4 泛型数组作为泛型类中的参数

ios - 串行调度队列如何保证资源保护?

ios - Obj-C 中的 3D Touch Home 快捷方式

ios - CNContactVCardSerialization.dataWithContacts 给出异常

ios - 选择 Collection View 中的单元格到新 Controller

swift - 更改图 block 的 zPosition

ios - Xamarin iOS : Doesn't make any sound using AVSpeechSynthesizer?

ios - 加载 uiviewcontroller 后更新 xib View 的位置?