Class: Ruby2D::Line

Inherits:
Object
  • Object
show all
Includes:
Renderable
Defined in:
lib/ruby2d/line.rb

Instance Attribute Summary collapse

Attributes included from Renderable

#color, #height, #x, #y, #z

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Renderable

#a, #a=, #add, #b, #b=, #g, #g=, #opacity, #opacity=, #r, #r=, #remove

Constructor Details

#initialize(opts = {}) ⇒ Line

Returns a new instance of Line.



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/ruby2d/line.rb', line 9

def initialize(opts = {})
  @x1 = opts[:x1] || 0
  @y1 = opts[:y1] || 0
  @x2 = opts[:x2] || 100
  @y2 = opts[:y2] || 100
  @z = opts[:z] || 0
  @width = opts[:width] || 2
  self.color = opts[:color] || 'white'
  self.opacity = opts[:opacity] if opts[:opacity]
  add
end

Instance Attribute Details

#widthObject

Returns the value of attribute width.



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

def width
  @width
end

#x1Object

Returns the value of attribute x1.



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

def x1
  @x1
end

#x2Object

Returns the value of attribute x2.



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

def x2
  @x2
end

#y1Object

Returns the value of attribute y1.



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

def y1
  @y1
end

#y2Object

Returns the value of attribute y2.



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

def y2
  @y2
end

Class Method Details

.draw(opts = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/ruby2d/line.rb', line 41

def self.draw(opts = {})
  ext_draw([
    opts[:x1], opts[:y1], opts[:x2], opts[:y2], opts[:width],
    opts[:color][0][0], opts[:color][0][1], opts[:color][0][2], opts[:color][0][3],
    opts[:color][1][0], opts[:color][1][1], opts[:color][1][2], opts[:color][1][3],
    opts[:color][2][0], opts[:color][2][1], opts[:color][2][2], opts[:color][2][3],
    opts[:color][3][0], opts[:color][3][1], opts[:color][3][2], opts[:color][3][3]
  ])
end

Instance Method Details

#color=(c) ⇒ Object



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

def color=(c)
  @color = Color.set(c)
  update_color(@color)
end

#contains?(x, y) ⇒ Boolean

Line contains a point if the point is closer than the length of line from both ends and if the distance from point to line is smaller than half of the width. For reference:

https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line

Returns:

  • (Boolean)


35
36
37
38
39
# File 'lib/ruby2d/line.rb', line 35

def contains?(x, y)
  points_distance(x1, y1, x, y) <= length &&
  points_distance(x2, y2, x, y) <= length &&
  (((@y2 - @y1) * x - (@x2 - @x1) * y + @x2 * @y1 - @y2 * @x1).abs / length) <= 0.5 * @width
end

#lengthObject

Return the length of the line



27
28
29
# File 'lib/ruby2d/line.rb', line 27

def length
  points_distance(@x1, @y1, @x2, @y2)
end