Skip to content

Instantly share code, notes, and snippets.

@rnapier
Created September 14, 2016 17:07
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 rnapier/75983a0f8c9267094eddad3c2f056d94 to your computer and use it in GitHub Desktop.
Save rnapier/75983a0f8c9267094eddad3c2f056d94 to your computer and use it in GitHub Desktop.
Point and vector operations
// Vectors can be inverted
private prefix func - (operand: CGVector) -> CGVector {
return CGVector(dx: -operand.dx, dy: -operand.dy)
}
// Vectors can be added and subtracted
private func + (lhs: CGVector, rhs: CGVector) -> CGVector {
return CGVector(dx: lhs.dx + rhs.dx, dy: lhs.dy + rhs.dy)
}
private func - (lhs: CGVector, rhs: CGVector) -> CGVector {
return lhs + (-rhs)
}
// Points can be offset by vectors (commutative)
private func + (lhs: CGPoint, rhs: CGVector) -> CGPoint {
return CGPoint(x: lhs.x + rhs.dx, y: lhs.y + rhs.dy)
}
private func + (lhs: CGVector, rhs: CGPoint) -> CGPoint {
return rhs + lhs
}
private func - (lhs: CGPoint, rhs: CGVector) -> CGPoint {
return lhs + (-rhs)
}
// The difference between a point and a point is a vector.
private func - (lhs: CGPoint, rhs: CGPoint) -> CGVector {
return CGVector(dx: lhs.x - rhs.x, dy: lhs.y - rhs.y)
}
// Vectors can be scaled by a scalar (commutative)
private func * (lhs: CGFloat, rhs: CGVector) -> CGVector {
return CGVector(dx: rhs.dx * lhs, dy: rhs.dy * lhs)
}
private func * (lhs: CGVector, rhs: CGFloat) -> CGVector {
return rhs * lhs
}
// Vectors can be scaled by the reciprocal of a scalar
private func / (lhs: CGVector, rhs: CGFloat) -> CGVector {
return 1.0/rhs * lhs
}
// Points can be scaled by a scalar (commutative). (FIXME: Is this really true?)
private func * (lhs: CGFloat, rhs: CGPoint) -> CGPoint {
return CGPoint(x: rhs.x * lhs, y: rhs.y * lhs)
}
private func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return rhs * lhs
}
// Points can be scaled by the reciprocol of a scalar
private func / (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return 1.0/rhs * lhs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment