所有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"])
)
}
}
我希望节点从上到下,而不是相反。哎哟,我想看到顶部的“欢迎”标签,然后是“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.
从这张图中我们可以看到,要将 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/