2

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 pathOfShapevariable. 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))

user594883
  • 1,329
  • 2
  • 17
  • 36
  • Since you did not change the `position` property of the shape, it's still at the default value, (0, 0). Adding a `CGPath` to the shape does not change its position. The path is rendered relative to (0, 0). – 0x141E Jul 11 '16 at 16:24
  • @0x141E But the SKShapeNode is not in 0,0 but exactly where the user draw it – user594883 Jul 11 '16 at 18:47
  • The path is drawn _relative_ to (0, 0). The points in the polygon can have any value (in the scene) but the _origin_ of the `CGPath` is the position of the shape node. – 0x141E Jul 11 '16 at 18:51
  • @0x141E So inorder to get the position of the shape, I have to get it from the path? – user594883 Jul 12 '16 at 13:49
  • You can save the points of the polygon in an array as the user taps on the screen and then compute the centroid of the points in the array. – 0x141E Jul 12 '16 at 16:52

1 Answers1

1

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)

enter image description here

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.

Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133