Reputation: 682
All SKSpriteNode
s have their origin, also called anchorPoint
, if I'm not wrong, in their middle. I want to translate that origin to be in the middle of the top line of the node. I've tried the following inside the init()
method, but it doesn't work:
self.anchorPoint = self.anchorPoint.applying(
CGAffineTransform.init(translationX: 0, y: self.frame.size.height/2)
)
PS: I'm using this to simplify the following:
I've created an array of SpriteNodes, which all have are in the new CGPoint.zero
position, then, i'll have to apply this on them:
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"])
)
}
}
Here's the pic of what the code compiles to:
I want the nodes to go from up to down, not the other way around. Iow, I wanna see the "Welcome" Label at the top, then the "texT" one, then the others.
Upvotes: 2
Views: 1066
Reputation: 274490
According to the docs,
This is how anchor points work:
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.
From this image, we can see that to set the anchor point to the middle of the top border, you need to set it to (0.5, 1)
.
You tried to transform the anchor point to self.frame.size / 2
which is probably a number larger than 1. Well, according to the docs, the range of (0, 0) - (1, 1)
covers the whole frame of the sprite node. If you set it to a value larger than (1, 1), the anchor point will be outside of the frame of the node.
Upvotes: 4