Skip to content

Instantly share code, notes, and snippets.

@veeneck
Last active July 7, 2017 13:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veeneck/8a12a23f673d410359ca96b8978a913f to your computer and use it in GitHub Desktop.
Save veeneck/8a12a23f673d410359ca96b8978a913f to your computer and use it in GitHub Desktop.
Launch Trajectory in Swift and SpriteKit
/// Uses physics equations to calculate position of projectile at given time.
/// This tool is awesome to explain what's happening, and play with sample data:
/// http://hyperphysics.phy-astr.gsu.edu/hbase/traj.html#tra6
func launchAtPoint(angle:CGFloat, start:CGPoint, end:CGPoint, node:SKNode) -> SKAction {
/// Constants
let gravity : Double = 9.8
let pixelsToMeters : CGFloat = 50
/// Calculate everything we can given an angle and an end point
let launchAngle = angle.degreesToRadians()
let distance = start.distanceTo(point: end)
let adjustedRange = Double(distance / pixelsToMeters)
let launchVelocity = sqrt((adjustedRange * gravity) / Double(sin(launchAngle * 2)))
let initialVerticalVelocity = launchVelocity * Double(sin(launchAngle))
let travelTime = CGFloat((2 * initialVerticalVelocity) / gravity)
/// X and Y just go in straight line to point over time, while fake Z value gives the height
let dx = (end.x - start.x) / travelTime
let dy = (end.y - start.y) / travelTime
let launch = SKAction.customAction(withDuration: TimeInterval(travelTime)) { node, time in
/// Get the vertical change at this point in time
let change = Double(0.5 * gravity * Double(time * time))
let currentZ = CGFloat(initialVerticalVelocity * Double(time)) - CGFloat(change)
/// X just updates along straight line to point
node.position.x = start.x + (dx * time)
/// Y also goes in straight line to point, but then add in our fake Z value adjust for metters to pixels
node.position.y = start.y + (dy * time) + CGFloat(currentZ * pixelsToMeters)
}
return launch
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment