我在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))
答案 0 :(得分:1)
实际上,如果你制作一个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),但几乎你知道你的形状在哪里。