Class: Sangaku::Line

Inherits:
Object
  • Object
show all
Defined in:
lib/sangaku/line.rb

Instance Method Summary collapse

Constructor Details

#initialize(p1, p2) ⇒ Line

Returns a new instance of Line.



5
6
7
# File 'lib/sangaku/line.rb', line 5

def initialize(p1, p2)
  @coords = Point::convert([p1, p2])
end

Instance Method Details

#+(point) ⇒ Object



42
43
44
# File 'lib/sangaku/line.rb', line 42

def +(point)
  Line.new(p1 + point, p2 + point)
end

#-(point) ⇒ Object



45
46
47
# File 'lib/sangaku/line.rb', line 45

def -(point)
  Line.new(p1 - point, p2 - point)
end

#contain?(x = nil, y = nil) ⇒ Boolean

Returns:

  • (Boolean)


61
62
63
64
# File 'lib/sangaku/line.rb', line 61

def contain?(x = nil, y = nil)
  (x.nil? || x.between?(*[p1.x, p2.x].sort)) &&
  (y.nil? || y.between?(*[p1.y, p2.y].sort))
end

#cross(other) ⇒ Object



57
58
59
# File 'lib/sangaku/line.rb', line 57

def cross(other)
  self.vx * other.vy - self.vy * other.vx
end

#dot(other) ⇒ Object



53
54
55
# File 'lib/sangaku/line.rb', line 53

def dot(other)
  (self.vx * other.vx + self.vy * other.vy)/(self.length * other.length)
end

#get_x(y) ⇒ Object



33
34
35
36
# File 'lib/sangaku/line.rb', line 33

def get_x(y)
  ratio = p1.y != p2.y ? (y-p1.y)/(p2.y-p1.y).to_f : 0.5
  p1.x + ratio * (p2.x-p1.x)
end

#get_y(x) ⇒ Object



37
38
39
40
# File 'lib/sangaku/line.rb', line 37

def get_y(x)
  ratio = p1.x != p2.x ? (x-p1.x)/(p2.x-p1.x).to_f : 0.5
  p1.y + ratio * (p2.y-p1.y)
end

#hObject



17
18
19
# File 'lib/sangaku/line.rb', line 17

def h
  (p2.y - p1.y).abs
end

#lengthObject



21
22
23
# File 'lib/sangaku/line.rb', line 21

def length
  Math.sqrt(vx ** 2 + vy ** 2)
end

#midObject



49
50
51
# File 'lib/sangaku/line.rb', line 49

def mid
  (p1 + p2) * 0.5
end

#p1Object



9
# File 'lib/sangaku/line.rb', line 9

def p1; @coords[0]; end

#p1=(val) ⇒ Object



10
# File 'lib/sangaku/line.rb', line 10

def p1=(val); @coords[0] = val; end

#p2Object



11
# File 'lib/sangaku/line.rb', line 11

def p2; @coords[1]; end

#p2=(val) ⇒ Object



12
# File 'lib/sangaku/line.rb', line 12

def p2=(val); @coords[1] = val; end

#to_aObject



66
67
68
# File 'lib/sangaku/line.rb', line 66

def to_a
  [@p1.to_a, @p2.to_a]
end

#to_sObject Also known as: inspect



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

def to_s
  "#{p1}->#{p2}"
end

#vxObject



25
26
27
# File 'lib/sangaku/line.rb', line 25

def vx
  p2.x - p1.x
end

#vyObject



29
30
31
# File 'lib/sangaku/line.rb', line 29

def vy
  p2.y - p1.y
end

#wObject



14
15
16
# File 'lib/sangaku/line.rb', line 14

def w
  (p2.x - p1.x).abs
end