Search code examples
swiftsprite-kitskspritenode

Starting position of a Sprite Node


I am using to following code to make a sprite node move in a circle in Xcode spritekit.

let circleDiameter = CGFloat(100)
// center our path based on our sprites initial position
let pathCenterPoint = CGPoint(
    x: object.position.x - circleDiameter,
    y: object.position.y - circleDiameter/2)
// create the path our sprite will travel along
let circlePath = CGPath(ellipseIn: CGRect(origin: pathCenterPoint, size: CGSize(width: circleDiameter, height: circleDiameter)), transform: nil)
// create a followPath action for our sprite
let followCirclePath = SKAction.follow(circlePath, asOffset: false, orientToPath: false, duration: 3)
// make our sprite run this action forever
object.run(SKAction.repeatForever(followCirclePath).reversed(), withKey: “moving”)

       world.addChild(object)

The problem is, the sprite node starting position is always positioned on the RIGHT side of the circle path. I know I can use .reversed() to change direction of the sprite node but that is not what I am asking.

How can I change the "starting point" to the LEFT side of the circle path?

Thanks Guys! Please refer to the picture below :D

Example of Question


Solution

  • CGPath(ellipseIn:...) is an utility method which creates a path of an ellipse, where the "argument" or "angle" runs from 0 to 2π.

    You cannot add an "offset" to the follow action, but you can define the path in a way that it starts at the "left end" of the circle:

    let circlePath = CGMutablePath()
    circlePath.addArc(center: pathCenterPoint, radius: circleDiameter,
                      startAngle: -.pi, endAngle: .pi, clockwise: false)