Skip to content

Instantly share code, notes, and snippets.

@chunkyguy
Created January 20, 2015 11:48
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save chunkyguy/d3aa8b27ace2abd44f4b to your computer and use it in GitHub Desktop.
import UIKit
func clamp<T:Comparable>(value:T, lowerBound:T, upperBound:T) -> T {
return min(max(lowerBound, value), upperBound)
}
func clamp(value:Vector2, lowerBound:Vector2, upperBound:Vector2) -> Vector2 {
return min(max(lowerBound, value), upperBound)
}
struct Vector2 {
var x : Float = 0.0
var y : Float = 0.0
init(x:Float = 0,y:Float = 0) {
self.x = x
self.y = y
}
}
func ==(lhs: Vector2, rhs: Vector2) -> Bool {
return (lhs.x == rhs.x) && (lhs.y == rhs.y)
}
func < (lhs: Vector2, rhs: Vector2) -> Bool {
return (lhs.x < rhs.x) && (lhs.y < rhs.y)
}
func <= (lhs: Vector2, rhs: Vector2) -> Bool {
return (lhs.x <= rhs.x) && (lhs.y <= rhs.y)
}
func >= (lhs: Vector2, rhs: Vector2) -> Bool {
return (lhs.x >= rhs.x) && (lhs.y >= rhs.y)
}
func > (lhs: Vector2, rhs: Vector2) -> Bool {
return (lhs.x > rhs.x) && (lhs.y > rhs.y)
}
extension Vector2 : Comparable {}
func min(lhs: Vector2, rhs: Vector2) -> Vector2 {
return Vector2(x: min(lhs.x, rhs.x), y: min(lhs.y, rhs.y))
}
func max(lhs: Vector2, rhs: Vector2) -> Vector2 {
return Vector2(x: max(lhs.x, rhs.x), y: max(lhs.y, rhs.y))
}
let lowerBound = Vector2(x: -100, y: -100)
let upperBound = Vector2(x: 100, y: 100)
let test1 = clamp(Vector2(x: 200, y: 200), lowerBound, upperBound)
let test2 = clamp(Vector2(x: -200, y: -200), lowerBound, upperBound)
let test3 = clamp(Vector2(x: -10, y: -134), lowerBound, upperBound)
let test4 = clamp(Vector2(x: 10, y: 134), lowerBound, upperBound)
let test5 = min(Vector2(x: -10, y: -134), lowerBound)
let test6 = max(Vector2(x: 10, y: 134), upperBound)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment