Class: Osb::Vector2

Inherits:
Object
  • Object
show all
Defined in:
lib/osb/vector2.rb

Overview

Represents a 2d point or vector.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(x = 0, y = 0) ⇒ Vector2

Returns a new instance of Vector2.

Parameters:

  • x (Numeric, Array<Numeric>) (defaults to: 0)

    x coordinate of this {Vector2}, or an Array of 2 numbers.

  • y (Numeric) (defaults to: 0)

    y coordinate of this {Vector2}



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/osb/vector2.rb', line 15

def initialize(x = 0, y = 0)
  Internal.assert_type!(x, [Numeric, Internal::T[Array][Numeric]], "x")
  Internal.assert_type!(y, Numeric, "y")

  if x.is_a?(Array)
    if x.size != 2
      raise InvalidValueError, "Must be an Array of 2 Numeric values."
    end
    @x = x[0]
    @y = x[1]
  else
    @x = x
    @y = y
  end
end

Instance Attribute Details

#xObject

Returns x coordinate of this vector.

Returns:

  • x coordinate of this vector



7
8
9
# File 'lib/osb/vector2.rb', line 7

def x
  @x
end

#yObject

Returns y coordinate of this vector.

Returns:

  • y coordinate of this vector



7
8
9
# File 'lib/osb/vector2.rb', line 7

def y
  @y
end

Instance Method Details

#!=(vector) ⇒ Boolean

Returns whether two {Vector2} are not equal within tolerance

Parameters:

Returns:

  • (Boolean)


58
59
60
# File 'lib/osb/vector2.rb', line 58

def !=(vector)
  !(self == vector)
end

#+(vector) ⇒ Vector2

Add another {Vector2} to this one.

Parameters:

Returns:



34
35
36
37
# File 'lib/osb/vector2.rb', line 34

def +(vector)
  Internal.assert_type!(vector, Vector2, "vector")
  Vector2.new(self.x + vector.x, self.y + vector.y)
end

#-(vector) ⇒ Vector2

Subtract another {Vector2} from this one.

Parameters:

Returns:



42
43
44
45
# File 'lib/osb/vector2.rb', line 42

def -(vector)
  Internal.assert_type!(vector, Vector2, "vector")
  Vector2.new(self.x - vector.x, self.y - vector.y)
end

#==(vector) ⇒ Boolean

Returns whether two {Vector2} are equal within tolerance

Parameters:

Returns:

  • (Boolean)


50
51
52
53
# File 'lib/osb/vector2.rb', line 50

def ==(vector)
  Internal.assert_type!(vector, Vector2, "vector")
  Math.fuzzy_equal(self.x, vector.x) && Math.fuzzy_equal(self.y, vector.y)
end

#cloneVector2

Makes a copy of this {Vector2}.

Returns:



64
65
66
# File 'lib/osb/vector2.rb', line 64

def clone
  Vector2.new(self.x, self.y)
end

#lengthFloat

Returns the length of this {Vector2}.

Returns:

  • (Float)


82
83
84
# File 'lib/osb/vector2.rb', line 82

def length
  Math.sqrt(self.x**2 + self.y**2)
end

#to_aArray(Float, Float)

Retrieves the coordinates in an Array.

Returns:

  • (Array(Float, Float))


70
71
72
# File 'lib/osb/vector2.rb', line 70

def to_a
  [self.x, self.y]
end

#to_sString

Returns a string representation of this {Vector2}.

Returns:

  • (String)


76
77
78
# File 'lib/osb/vector2.rb', line 76

def to_s
  self.to_a.to_s
end