Module: Vector2d::Fitting
- Included in:
- Vector2d
- Defined in:
- lib/vector2d/fitting.rb
Instance Method Summary collapse
-
#contain(other) ⇒ Object
Scales down the given vector unless it fits inside.
-
#fit(other) ⇒ Object
(also: #constrain_both)
Scales the vector to fit inside another vector, retaining the aspect ratio.
-
#fit_either(other) ⇒ Object
(also: #constrain_one)
Constrain/expand so that one of the coordinates fit within (the square implied by) another vector.
Instance Method Details
#contain(other) ⇒ Object
Scales down the given vector unless it fits inside.
vector = Vector2d(20, 20)
vector.contain(Vector2d(10, 10)) # => Vector2d(10,10)
vector.contain(Vector2d(40, 20)) # => Vector2d(20,10)
vector.contain(Vector2d(20, 40)) # => Vector2d(10,20)
13 14 15 16 |
# File 'lib/vector2d/fitting.rb', line 13 def contain(other) v, _ = coerce(other) (v.x > x || v.y > y) ? other.fit(self) : other end |
#fit(other) ⇒ Object Also known as: constrain_both
Scales the vector to fit inside another vector, retaining the aspect ratio.
vector = Vector2d(20, 10)
vector.fit(Vector2d(10, 10)) # => Vector2d(10,5)
vector.fit(Vector2d(20, 20)) # => Vector2d(20,10)
vector.fit(Vector2d(40, 40)) # => Vector2d(40,20)
Note: Either axis will be disregarded if zero or nil. This is a feature, not a bug.
27 28 29 30 31 |
# File 'lib/vector2d/fitting.rb', line 27 def fit(other) v, _ = coerce(other) scale = v.to_f_vector / self self * ((scale.y == 0 || (scale.x > 0 && scale.x < scale.y)) ? scale.x : scale.y) end |
#fit_either(other) ⇒ Object Also known as: constrain_one
Constrain/expand so that one of the coordinates fit within (the square implied by) another vector.
constraint = Vector2d(5, 5)
Vector2d(20, 10).fit_either(constraint) # => Vector2d(10,5)
Vector2d(10, 20).fit_either(constraint) # => Vector2d(5,10)
40 41 42 43 44 45 46 47 48 49 |
# File 'lib/vector2d/fitting.rb', line 40 def fit_either(other) v, _ = coerce(other) scale = v.to_f_vector / self if (scale.x > 0 && scale.y > 0) scale = (scale.x < scale.y) ? scale.y : scale.x self * scale else fit(v) end end |