47 lines
845 B
Nim
47 lines
845 B
Nim
import math
|
|
import strformat
|
|
|
|
type
|
|
Vector* = object
|
|
x*: float
|
|
y*: float
|
|
|
|
func vector*(x, y: float): Vector =
|
|
Vector(x: x, y: y)
|
|
|
|
func `+`*(a, b: Vector): Vector =
|
|
Vector(x: a.x + b.x, y: a.y + b.y)
|
|
|
|
func `-`*(a: Vector): Vector =
|
|
Vector(x: -a.x, y: -a.y)
|
|
|
|
func `-`*(a, b: Vector): Vector =
|
|
a + (-b)
|
|
|
|
func `*`*(a: Vector, f: float): Vector =
|
|
Vector(x: a.x * f, y: a.y * f)
|
|
|
|
func `*`*(f: float, a: Vector): Vector =
|
|
a * f
|
|
|
|
func dot*(a, b: Vector): float =
|
|
a.x * b.x + a.y * b.y
|
|
|
|
func len*(a: Vector): float =
|
|
sqrt(dot(a, a))
|
|
|
|
func `/`*(a: Vector, f: float): Vector =
|
|
a * (1/f)
|
|
|
|
func normalize*(a: Vector): Vector =
|
|
a / a.len
|
|
|
|
func `+=`*(a: var Vector, b: Vector) =
|
|
a = a + b
|
|
|
|
func `-=`*(a: var Vector, b: Vector) =
|
|
a = a - b
|
|
|
|
func `$`*(a: Vector): string =
|
|
&"[{a.x}, {a.y}]"
|