Search code examples
swiftsprite-kitskactioncgpath

Making a half circle path with CGPath, and follow the path with SKAction


I have no idea how to make a half circle path with CGPath. There is the code i have:

  let path = CGPathCreateMutable()
  let Width: CGFloat = 38.0
  let radius: CGFloat = (Width / 2.0) + (Treshold / 2.0)
  CGPathAddArc(pathOne, nil, x, 0.0, radius, firstPoint.position.x, secondPoint.position.x, true)
  let waitAction = SKAction.waitForDuration(1.0)
  let moveAction = SKAction.followPath(pathOne, duration: 3.0)
  capOne.runAction(SKAction.sequence([waitAction, moveAction]))

Solution

  • import SpriteKit
    
    class GameScene: SKScene, SKPhysicsContactDelegate {
    
        override init(size: CGSize) {
            super.init(size: size)
            let square = SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(20, 20))
            square.position = CGPointMake(self.size.width/2, self.size.height/2)
            addChild(square)
    
            let bezierPath = UIBezierPath(arcCenter: CGPointMake(0, 0), radius: 100, startAngle: CGFloat(M_PI_2), endAngle: CGFloat(-M_PI_2), clockwise: false)
    
            let pathNode = SKShapeNode(path: bezierPath.CGPath)
            pathNode.strokeColor = SKColor.blueColor()
            pathNode.lineWidth = 3
            pathNode.position = square.position
            addChild(pathNode)
    
            square.runAction(SKAction.followPath(bezierPath.CGPath, asOffset: true, orientToPath: true, duration: 2))
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }