Skip to content

Instantly share code, notes, and snippets.

@Tokuriku
Last active August 29, 2015 14:24
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 Tokuriku/502d31cd31310265b127 to your computer and use it in GitHub Desktop.
Save Tokuriku/502d31cd31310265b127 to your computer and use it in GitHub Desktop.
Clamp Velocity of an SKNode's PhysicsBody
/* Clamp Velocity */
// Set the initial parameters
let maxVelocity = CGFloat(100)
let deltaX = (self.physicsBody?.velocity.dx)!
let deltaY = (self.physicsBody?.velocity.dy)!
// Get the actual length of the vector with Pythagorean Theorem
let deltaZ = sqrt(pow(deltaX, 2) + pow(deltaY, 2))
// If the vector length is higher then the max velocity
if deltaZ > maxVelocity {
// Get the proportions for X and Y axis compared to the Z of the Pythagorean Theorem
let xProportion = deltaX / deltaZ
let yProportion = deltaY / deltaZ
// Get a new X and Y length in proportion to the max velocity
let correctedDeltaX = xProportion * maxVelocity
let correctedDeltaY = yProportion * maxVelocity
// Assign the new velocity to the Node
self.physicsBody?.velocity = CGVector(dx: correctedDeltaX, dy: correctedDeltaY)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment