iosswiftsprite-kitswift3skspritenode

SKSpriteNode will not center


I have this inside my GameScene which is called in the didMove()

for i in 1...5 {

    // path to create the circle
    let path = UIBezierPath(arcCenter: CGPoint(x: center.x, y: center.y), radius: CGFloat(((43 * i) + 140)), startAngle: CGFloat(GLKMathDegreesToRadians(-50)), endAngle: CGFloat(M_PI * 2), clockwise: false)

    // the inside edge of the circle used for creating its physics body
    let innerPath = UIBezierPath(arcCenter: CGPoint(x: center.x, y: center.y), radius: CGFloat(((43 * i) + 130)), startAngle: CGFloat(GLKMathDegreesToRadians(-50)), endAngle: CGFloat(M_PI * 2), clockwise: false)

    // create a shape from the path and customize it
    let shape = SKShapeNode(path: path.cgPath)
    shape.lineWidth = 20
    shape.strokeColor = UIColor(red:0.98, green:0.99, blue:0.99, alpha:1.00)

    // create a texture and apply it to the sprite
    let trackViewTexture = self.view!.texture(from: shape)
    let trackViewSprite = SKSpriteNode(texture: trackViewTexture)
    trackViewSprite.physicsBody = SKPhysicsBody(edgeChainFrom: innerPath.cgPath)
    self.addChild(trackViewSprite)

}

It uses UIBezierPaths to make a few circles. It converts the path into a SKShapeNode then a SKTexture and then applies it to the final SKSpriteNode.

When I do this, the SKSpriteNode is not where it should be, it is a few to the right:

enter image description here

But when I add the SKShapeNode I created, it is set perfectly fine to where it should be:

enter image description here

Even doing this does not center it!

trackViewSprite.position = CGPoint(x: 0, y: 0)

No matter what I try it just will not center.

Why is this happening? Some sort of bug when converting to a texture?

P.S - This has something to do with this also Keep relative positions of SKSpriteNode from SKShapeNode from CGPath But there is also no response :(

Edit, When I run this:

let testSprite = SKSpriteNode(color: UIColor.yellow, size: trackViewSprite.size)
self.addChild(testSprite)

It shows it has the same frame also: enter image description here


Solution

  • After a long discussion, we determined that the problem is due to the frame size not being the expected size of the shape.

    To combat this, the OP created an outer path of his original path, and calculated the frame that would surround this. Now this approach may not work for everybody.

    If anybody else comes across this issue, they will need to do these things:

    1) Check the frame of the SKShapeNode to make sure that it is correct
    2) Determine what method is best to calculate the correct desired frame
    3) Use this new frame when getting textureFromNode to extract only the desired texture size