CAShapeLayer and CGPath are following two different coordinate systems

I am working on SpriteKit, using Swift. I am trying to move a dot on a visible circular path. For this I have made a function, which takes the input SKShapeNode and makes it move along the shapeLayer.path.

Individually, both are working fine. The dot is successfully moving on the circular path I want and is exactly where I want. Also, CAShapeLayer is drawing the circular path exactly as I like, but it is drawing it at a different position (the centre is not the desired one).

 func addOrbitingToShape(shape: SKShapeNode, orbitSize: CGSize, reverseOrbit: Bool, duration: NSTimeInterval) {

            let orbitPathOrigin = CGPoint(x: center.x - orbitSize.width/2, y: center.y - orbitSize.height/2)
            let orbitPathRect = CGRect(origin: orbitPathOrigin, size: orbitSize)
            let orbitPath = CGPathCreateWithEllipseInRect(orbitPathRect, nil)

            let shapeLayer = CAShapeLayer()
            shapeLayer.path = orbitPath
            shapeLayer.strokeColor = UIColor.whiteColor().CGColor
            shapeLayer.lineWidth = 0.5
            shapeLayer.fillColor = UIColor.clearColor().CGColor

            if reverseOrbit == false {
                let orbitActionTwo = SKAction.followPath(shapeLayer.path, asOffset: false, orientToPath: true, duration: duration)

            } else if reverseOrbit == true {
                let orbitActionTwo = SKAction.followPath(shapeLayer.path, asOffset: false, orientToPath: true, duration: duration)

My guess is, view.layer.addSubLayer() is creating a layer which is of completely different size than of my game’s view and hence the difference. The way I set my view is the following code added in GameViewController in viewDidLoad:

// Detect the screensize
    var sizeRect = UIScreen.mainScreen().applicationFrame
    var width = sizeRect.size.width * UIScreen.mainScreen().scale
    var height = sizeRect.size.height * UIScreen.mainScreen().scale

    // Create a fullscreen Scene object
    scene = GameScene(size: CGSizeMake(width, height))
    scene!.scaleMode = .AspectFill

    // Configure the view.
    let skView = self.view as! SKView

Kindly help. I’m unable to find a solution for this.

Source: ios

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.