Launch Trajectory in Swift and SpriteKit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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