Sha256: efb4ee7c00ee777cddd1a02367a91098bfa16c51729e1f5de13f6abb76a600d2

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

class GeometricLine < Struct.new(:point1, :point2)

  def self.new_by_arrays(point1_coordinates, point2_coordinates)
    self.new(GeometricPoint.new_by_array(point1_coordinates),
             GeometricPoint.new_by_array(point2_coordinates))
  end

  def angle_to(another_line)
    sa = Math::atan(slope)
    oa = Math::atan(another_line.slope)
    (sa-oa).abs
  end

  def distance_to(point)
    x0 = point.x
    y0 = point.y

    x1 = point1.x
    x2 = point2.x
    y1 = point1.y
    y2 = point2.y

    (((x2-x1)*(y1-y0))-((x1-x0)*(y2-y1))).abs/Math.sqrt((x2-x1)**2+(y2-y1)**2)
  end

  def horizontal?
    slope == 0
  end

  def intersect_x(another_line)
    if vertical? and another_line.vertical?
      if x_intercept == another_line.x_intercept
        return x_intercept
      else
        return nil
      end
    end

    return nil if horizontal? and another_line.horizontal?

    return x_intercept if vertical?
    return another_line.x_intercept if another_line.vertical?

    d_intercept = another_line.y_intercept - y_intercept
    d_slope = slope - another_line.slope

    d_intercept / d_slope
  end

  def parallel_to?(another_line)
    return true if slope.infinite? and another_line.slope.infinite?

    slope == another_line.slope
  end

  def slope
    dy = Float(point2.y - point1.y)
    dx = Float(point2.x - point1.x)

    return 0.0 if dy == 0

    dy / dx
  end

  def vertical?
    if slope.infinite?
      return true
    else
      return false
    end
  end

  def x_intercept
    return nil if horizontal?

    dx = point1.y / slope
    point1.x - dx
  end

  def y_intercept
    return nil if vertical?

    dy = point1.x * slope
    point1.y - dy
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flash_math-0.0.1 lib/flash_math/modules/geometry/geometric_line.rb