Swift: 如何获取SKShapeNode的位置?

Swift: How to get the position of SKShapeNode?

我在处理 SKShapeNode 的位置时遇到了问题。我正在存储用户触摸屏幕的路径。然后我创建一个多边形并将其放入 pathOfShape 变量中。我创建了该路径的 SKShapeNode 并且一切正常。我在屏幕上整齐地绘制了用户绘制的多边形。

不过我想在多边形上添加更多内容。出于某种原因,我无法获得 SKShapeNode 的位置。相反,如果我尝试使用 position 属性,它会指向 x:0.0、y:0.0,如下所示。这里发生了什么?我怎样才能得到我的 SKShapeNode 的实际 position

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)

结果为 Optional((0.0, 0.0))

实际上如果你做一个CGPath,比如一个三角形:

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)

并且您决定基于此路径创建 SKShapeNode

let shape = SKShapeNode(path: pathOfShape)

你可以要求得到这个形状的中心:

let center = CGPointMake(CGRectGetMidX(shape.frame),CGRectGetMidY(shape.frame))

正确的位置总是 (0.0, 0.0) 但几乎你知道你的形状在哪里。