Skip to content

Instantly share code, notes, and snippets.

@Groogy
Created July 16, 2017 14:14
Show Gist options
  • Save Groogy/b3a0e3576faa32f5fc72e62f00742ffb to your computer and use it in GitHub Desktop.
Save Groogy/b3a0e3576faa32f5fc72e62f00742ffb to your computer and use it in GitHub Desktop.
struct Vector2(Type)
SIZE = 2
TYPE = Type
ZERO = self.new()
ONE = self.new(1, 1)
property :x, :y
@x : Type
@y : Type
def initialize()
@x = Type.zero
@y = Type.zero
end
def initialize(@x : Type, @y : Type)
end
def initialize(tuple : Tuple(Type, Type))
@x = tuple[0]
@y = tuple[1]
end
def +(other : Vector2(Type))
self.class.new(@x + other.x, @y + other.y)
end
def -(other : Vector2(Type))
self.class.new(@x - other.x, @y + other.y)
end
def *(other : Vector2(Type))
self.class.new(@x * other.x, @y * other.y)
end
def /(other : Vector2(Type))
self.class.new(@x / other.x, @y / other.y)
end
def +(value : Type)
self.class.new(@x + value, @y + value)
end
def -(value : Type)
self.class.new(@x - value, @y - value)
end
def *(value : Type)
self.class.new(@x * value, @y * value)
end
def /(value : Type)
self.class.new(@x / value, @y / value)
end
def **(value : Type)
self.class.new(@x ** value, @y ** value)
end
def ==(other)
@x == other.x && @y == other.y
end
def !=(other)
!(self == other)
end
def -
self.class.new(-@x, -@y)
end
def [](index)
get(index)
end
def []=(index, value)
set(index, value)
end
def get(index)
if index == 0
@x
elsif index == 1
@y
else
raise IndexError.new
end
end
def set(index, value)
if index == 0
@x = value
elsif index == 1
@y = value
else
raise IndexError.new
end
end
def to_tuple
{@x, @y}
end
private macro def_conv_meth(name, type)
{% if type == TYPE %}
def {{name}}
self
end
{% else %}
def {{name}}
Vector2({{type}}).new(@x.{{name}}, @y.{{name}})
end
{% end %}
end
def_conv_meth(to_i8, Int8)
def_conv_meth(to_i16, Int16)
def_conv_meth(to_i32, Int32)
def_conv_meth(to_i64, Int64)
def_conv_meth(to_u8, UInt8)
def_conv_meth(to_u16, UInt16)
def_conv_meth(to_u32, UInt32)
def_conv_meth(to_u64, UInt64)
def_conv_meth(to_f32, Float32)
def_conv_meth(to_f64, Float64)
def_conv_meth(to_i, Int32)
def_conv_meth(to_u, UInt32)
def_conv_meth(to_f, Float64)
end
alias Vector2i8 = Vector2(Int8)
alias Vector2i16 = Vector2(Int16)
alias Vector2i32 = Vector2(Int32)
alias Vector2i64 = Vector2(Int64)
alias Vector2u8 = Vector2(UInt8)
alias Vector2u16 = Vector2(UInt16)
alias Vector2u32 = Vector2(UInt32)
alias Vector2u64 = Vector2(UInt64)
alias Vector2f32 = Vector2(Float32)
alias Vector2f64 = Vector2(Float64)
alias Vector2i = Vector2i32
alias Vector2u = Vector2u32
alias Vector2f = Vector2f64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment