Trevor Thomas
Trevor Thomas

Reputation: 79

Xcode Swift SKAction.follow start point

I am trying to make a spaceship orbit around a planet. I am currently doing

let playerPos = player.position
let planetPos = planet.position

let radius = playerPos.x - planetPos.x

let rect = CGRect(x: planetPos.x - radius, y: planetPos.y - radius, width: 2 * radius, height: 2 * radius)

let bezPath = UIBezierPath(roundedRect: rect, cornerRadius: 0)
let path = bezPath.cgPath

let shape = SKShapeNode(path: path)
shape.strokeColor = .blue
shape.zPosition = 10
self.addChild(shape)

let move = SKAction.follow(path, asOffset: false, orientToPath: true, speed: 200)

and this does create the correct path, screenshot

However, when I try to run the move action, the player teleports directly below the planet and then starts following the path. Is there a way to make it start following the path from where the player currently is? I am open to totally changing how I am going about making the ship move in a circle, as long as he starts where he is, and circles around a planet.

Upvotes: 3

Views: 444

Answers (2)

Trevor Thomas
Trevor Thomas

Reputation: 79

The solution was to use CGMutablePath instead

let dx = playerPos.x - planetPos.x
let dy = playerPos.y - planetPos.y
let currentTheta = atan(dy / dx)
let endTheta = currentTheta + CGFloat(Double.pi * 2)

let newPath = CGMutablePath.init()
newPath.move(to: player.position)
newPath.addArc(center: planetPos, radius: radius, startAngle: currentTheta, endAngle: endTheta, clockwise: false)

let move = SKAction.follow(newPath, asOffset: false, orientToPath: true, speed: 200)
player.run(SKAction.repeatForever(move))

The newPath.move(to: player.position) line starts the path at the ship's position and the newPath.addArc line draws a circle from the player's position and does a 360-degree rotation around the planet ending up back at the player's position.

Upvotes: 1

JohnV
JohnV

Reputation: 990

If I understand correctly, you would like the player to move from his current position to some position on the path, and then start following that path.

If so, you could consider running another action to first move the player from his current position to some starting point on the path, e.g. CGPoint(x: planetPos.x - radius, y: planetPos.y - radius). Then once the player is on that point, run the move action you have defined. You can use SKAction.sequence to run actions one after the other.

Hope this helps!

Upvotes: 0

Related Questions