Module: Vector2d::Transformations

Included in:
Vector2d
Defined in:
lib/vector2d/transformations.rb

Instance Method Summary collapse

Instance Method Details

#ceilObject

Rounds vector to up nearest integer.

Vector2d(2.4, 3.6).ceil # => Vector2d(3,4)


9
10
11
# File 'lib/vector2d/transformations.rb', line 9

def ceil
  self.class.new(x.ceil, y.ceil)
end

#clamp(min, max) ⇒ Object

Clamps the vector between two others, one axis at a time. The bounds are coerced, so scalars work too.

vector = Vector2d(2, 8)
vector.clamp(Vector2d(3, 3), Vector2d(6, 6)) # => Vector2d(3,6)
vector.clamp(3, 6)                           # => Vector2d(3,6)


20
21
22
23
24
# File 'lib/vector2d/transformations.rb', line 20

def clamp(min, max)
  min_v, = coerce(min)
  max_v, = coerce(max)
  self.class.new(x.clamp(min_v.x, max_v.x), y.clamp(min_v.y, max_v.y))
end

#floorObject

Rounds vector to up nearest integer.

Vector2d(2.4, 3.6).floor # => Vector2d(2,3)


30
31
32
# File 'lib/vector2d/transformations.rb', line 30

def floor
  self.class.new(x.floor, y.floor)
end

#normalizeObject

Normalizes the vector.

vector = Vector2d(2, 3)
vector.normalize        # => Vector2d(0.5547.., 0.8320..)
vector.normalize.length # => 1.0


40
41
42
# File 'lib/vector2d/transformations.rb', line 40

def normalize
  resize(1.0)
end

#perpendicularObject

Returns a perpendicular vector.

Vector2d(2, 3).perpendicular # => Vector2d(-3,2)


48
49
50
# File 'lib/vector2d/transformations.rb', line 48

def perpendicular
  Vector2d.new(-y, x)
end

#resize(new_length) ⇒ Object

Changes magnitude of vector.

Vector2d(2, 3).resize(1.0) # => Vector2d(0.5547.., 0.8320..)


56
57
58
# File 'lib/vector2d/transformations.rb', line 56

def resize(new_length)
  self * (new_length / length)
end

#reverseObject

Reverses the vector.

Vector2d(2, 3).reverse # => Vector2d(-2,-3)


64
65
66
# File 'lib/vector2d/transformations.rb', line 64

def reverse
  self.class.new(-x, -y)
end

#rotate(angle) ⇒ Object

Rotates the vector

Vector2d(1, 0).rotate(Math:PI/2) => Vector2d(1,0)


72
73
74
75
76
77
# File 'lib/vector2d/transformations.rb', line 72

def rotate(angle)
  Vector2d.new(
    (x * Math.cos(angle)) - (y * Math.sin(angle)),
    (x * Math.sin(angle)) + (y * Math.cos(angle))
  )
end

#round(digits = 0) ⇒ Object

Rounds vector to nearest integer.

Vector2d(2.4, 3.6).round # => Vector2d(2,4)
Vector2d(2.4444, 3.666).round(2) # => Vector2d(2.44, 3.67)


84
85
86
# File 'lib/vector2d/transformations.rb', line 84

def round(digits = 0)
  self.class.new(x.round(digits), y.round(digits))
end

#truncate(max) ⇒ Object

Truncates to max length if vector is longer than max.

vector = Vector2d(2.0, 3.0)
vector.truncate(5.0) # => Vector2d(2.0, 3.0)
vector.truncate(1.0) # => Vector2d(0.5547.., 0.8320..)


94
95
96
# File 'lib/vector2d/transformations.rb', line 94

def truncate(max)
  resize([max, length].min)
end