Reputation: 21
Im trying to get two SKshapeNodes to be positioned on the far left and far right of the screen without any part of the nodes offscreen like this https://i.sstatic.net/9rhAH.png. I don't want one node to be positioned according to the other node though. Ive been trying to use minX and maxX and use the width of the screen and SKshapeNodes and I can't figure it out.
This is what I have so far
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
let firstShapeNode = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 50, height: 50))
firstShapeNode.position = CGPoint(x: 0, y: self.frame.height / 2)
firstShapeNode.fillColor = SKColor.purpleColor()
self.addChild(firstShapeNode)
let secondShapeNode = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 50, height: 50))
secondShapeNode.position = CGPoint(x: 0, y: self.frame.height / 2)
secondShapeNode.fillColor = SKColor.cyanColor()
self.addChild(secondShapeNode)
}
Any suggestions?
Upvotes: 0
Views: 776
Reputation: 9787
To align the nodes to the left and right sides of the screen, respectively, try this:
firstShapeNode.position = CGPoint(x: firstShapeNode.size.width / 2, y: self.frame.height / 2)
secondShapeNode.position = CGPoint(x: self.frame.maxX - secondShapeNode.size.width / 2, y: self.frame.height / 2)
In SpriteKit, unlike UIKit, the default origin (0,0) point on the screen is in the bottom left corner. Additionally, by default, the position
of an SKNode
is the center of the node, which is why they need to be offset by half of their width.
Upvotes: 1