Instantly share code, notes, and snippets.

Embed
What would you like to do?
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