【问题标题】:Swift: How to get the position of SKShapeNode?Swift:如何获得 SKShapeNode 的位置?
【发布时间】:2016-07-11 13:26:01
【问题描述】:

我对 SKShapeNode 的位置有疑问。我正在存储用户触摸屏幕的路径。然后我创建一个多边形并将其放入pathOfShapevariable。我创建了该路径的 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))

【问题讨论】:

  • 由于您没有更改形状的position 属性,它仍然是默认值,(0, 0)。向形状添加CGPath 不会改变其位置。路径相对于 (0, 0) 呈现。
  • @0x141E 但是 SKShapeNode 不在 0,0 中,而是在用户绘制它的位置
  • 路径被绘制为 relative 到 (0, 0)。多边形中的点可以具有任何值(在场景中),但 CGPathorigin 是形状节点的位置。
  • @0x141E 所以为了得到形状的位置,我必须从路径中得到它?
  • 您可以在用户点击屏幕时将多边形的点保存在数组中,然后计算数组中点的质心。

标签: ios swift sprite-kit cgpath skshapenode


【解决方案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) 但几乎你知道你的形状在哪里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多