Instantly share code, notes, and snippets.

# codelynx/Vector3D+Vector2D.swift Last active Nov 7, 2015

What would you like to do?
Swift 2.0: Vector3D Vector2D
 // // Geometry.swift // ZKit // // Created by Kaz Yoshikawa on 11/6/15. // // import Foundation import CoreGraphics infix operator ⨯ { associativity left precedence 150 } infix operator • { associativity left precedence 150 } // // Vector3D // struct Vector3D { var x: Float var y: Float var z: Float init(_ x: Float, _ y: Float, _ z: Float) { self.x = x; self.y = y; self.z = z } func length²() -> Float { return (x * x) + (y * y) + (z * z) } func length() -> Float { return sqrtf(self.length²()) } func normalized() -> Vector3D { let l = self.length() return Vector3D(x/l, y/l, z/l) } } func + (l: Vector3D, r: Vector3D) -> Vector3D { return Vector3D(l.x + r.x, l.y + r.y, l.z + r.z) } func - (l: Vector3D, r: Vector3D) -> Vector3D { return Vector3D(l.x - r.x, l.y - r.y, l.z - r.z) } func * (l: Vector3D, r: Float) -> Vector3D { return Vector3D(l.x * r, l.y * r, l.z * r) } func / (l: Vector3D, r: Float) -> Vector3D { return Vector3D(l.x / r, l.y / r, l.z / r) } func • (a: Vector3D, b: Vector3D) -> Float { // dot product return (a.x * b.x) + (a.y * b.y) + (a.z + b.z) } func ⨯ (a: Vector3D, b: Vector3D) -> Vector3D { // cross product return Vector3D( a.y * b.z - b.y * a.z, a.z * b.x - b.z * a.x, a.x * b.y - b.x * a.y) } func length²(lhs: Vector3D, _ rhs: Vector3D) -> Float { return powf(rhs.x - lhs.x, 2.0) + powf(rhs.y - lhs.y, 2.0) + powf(rhs.z - lhs.z, 2.0) } func length(lhs: Vector3D, _ rhs: Vector3D) -> Float { return sqrtf(length²(lhs, rhs)) } // // Vector2D // struct Vector2D { var x: Float var y: Float init(_ x: Float, _ y: Float) { self.x = x; self.y = y } func length²() -> Float { return (x * x) + (y * y) } func length() -> Float { return sqrtf(self.length²()) } func normalized() -> Vector2D { let l = self.length() return Vector2D(x/l, y/l) } } func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D { return Vector2D(lhs.x + rhs.x, lhs.y + rhs.y) } func - (lhs: Vector2D, rhs: Vector2D) -> Vector2D { return Vector2D(lhs.x - rhs.x, lhs.y - rhs.y) } func * (lhs: Vector2D, rhs: Float) -> Vector2D { return Vector2D(lhs.x * rhs, lhs.y * rhs) } func / (lhs: Vector2D, rhs: Float) -> Vector2D { return Vector2D(lhs.x / rhs, lhs.y / rhs) } func • (lhs: Vector2D, rhs: Vector2D) -> Float { // dot product return lhs.x * rhs.y - lhs.y * rhs.x } func ⨯ (lhs: Vector2D, rhs: Vector2D) -> Float { // cross product return lhs.x * rhs.y - lhs.y * rhs.x } func length²(lhs: Vector2D, _ rhs: Vector2D) -> Float { return pow(rhs.x - lhs.x, 2.0) + pow(rhs.y - lhs.y, 2.0) } func length(lhs: Vector2D, _ rhs: Vector2D) -> Float { return sqrt(length²(lhs, rhs)) }