I'm having trouble with SKShapeNode's position. I'm storing a path from user touch of screen. Then I create a polygon of that and put it into pathOfShape
variable. I create SKShapeNode of that path and everything works fine. I get the user drawn polygon neatly drawn on screen.
However I would like to add more stuff on the polygon. For some reason I cannot get the position of the SKShapeNode. Instead if I try to use position
attribute, it points to x:0.0, y:0.0 like below. What's going one here? How can I get the actual position
of my SKShapeNode?
var pathOfShape = CGPathCreateMutable()
//path of polygon added here to pathOfShape
var shapeNode = SKShapeNode()
shapeNode.path = pathOfShape
shapeNode.name = "shape"
self.addChild(shapeNode)
let node1 = self.childNodeWithName("shape")
print(node1?.position)
results to Optional((0.0, 0.0))
Actually if you make a CGPath
, for example a triangle:
var pathOfShape = CGPathCreateMutable()
let center = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
CGPathMoveToPoint(pathOfShape, nil, center.x, center.y)
CGPathAddLineToPoint(pathOfShape, nil, center.x + 50, center.y + 50)
CGPathMoveToPoint(pathOfShape, nil, center.x + 50, center.y + 50)
CGPathAddLineToPoint(pathOfShape, nil, center.x - 50, center.y + 50)
CGPathMoveToPoint(pathOfShape, nil, center.x - 50, center.y + 50)
CGPathAddLineToPoint(pathOfShape, nil, center.x - 50, center.y - 50)
CGPathMoveToPoint(pathOfShape, nil, center.x - 50, center.y - 50)
CGPathAddLineToPoint(pathOfShape, nil, center.x, center.y)
CGPathCloseSubpath(pathOfShape)
And you decide to create a SKShapeNode
based from this path:
let shape = SKShapeNode(path: pathOfShape)
You could ask to get the center of this shape:
let center = CGPointMake(CGRectGetMidX(shape.frame),CGRectGetMidY(shape.frame))
The correct position is always (0.0, 0.0) but almost you know where is your shape.