cmi cmi - 7 months ago 81
Swift Question

How to create CGPath from a SKSpriteNode in SWIFT

I have a SKSpriteNode create with the level generator.


I need to create exactly the same shape using CGPath.

self.firstSquare = childNodeWithName("square") as! SKSpriteNode

var transform = CGAffineTransformMakeRotation(self.firstSquare.zRotation)
let rect = CGRect(origin: self.firstSquare.position, size: self.firstSquare.size)
let firstSquareCGPath:CGPath=CGPathCreateWithRect(rect, &transform)

=> firstSquare position (52.8359451293945, -52.9375076293945)

To check if my CGPath has been created as I want, I created a SKShapeNode with my CGPath:

let shape:SKShapeNode=SKShapeNode(path:path)
shape.fillColor = self.getRandomColor()

=> shape position (52.8359451293945, -52.9375076293945)

The result is not what I expected.

enter image description here

So I don't know if my CGPath is wrong, or if it's when I convert it in SKShapeNode that I lose the initial sprite properties.

To understand why I need to do that, please read this stack

EDIT 1,2

I added:

shape.position = self.firstSquare.position

And I obtained:

enter image description here

EDIT 3 :

I updated my explanations above, the anchor point of my firstSquare is now (0.5, 0.5)

cmi cmi

I found a solution, I need to use SKShapeNode(path:, centered:), then apply the transformation and set the position.

self.firstSquare = childNodeWithName("square") as! SKSpriteNode

let firstSquareCGPath:CGPath=CGPath(rect: CGRect(origin: self.firstSquare.position, size: self.firstSquare.size), transform: nil)

let shape:SKShapeNode=SKShapeNode(path: firstSquareCGPath, centered: true) //important
shape.zRotation = self.firstSquare.zRotation
shape.position = self.firstSquare.position
shape.fillColor =

It works perfectly!

Just a pending question, as I set the transformation and the position in last (because of the SKShapeNode properties), I don't know if my CGPath above is set correctly (like my SKSpriteNode).