Class: Coords::Cartesian2d

Inherits:
Object
  • Object
show all
Defined in:
lib/coords/cartesian2d.rb

Direct Known Subclasses

Cartesian3d

Instance Method Summary collapse

Constructor Details

#initialize(x, y) ⇒ Cartesian2d

Returns a new instance of Cartesian2d.



4
5
6
7
# File 'lib/coords/cartesian2d.rb', line 4

def initialize(x, y)
  @x = x
  @y = y
end

Instance Method Details

#==(point) ⇒ Object



36
37
38
# File 'lib/coords/cartesian2d.rb', line 36

def ==(point)
  x.round(12) == point.x.round(12) && y.round(12) == point.y.round(12)
end

#distance(point) ⇒ Object



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

def distance(point)
  Math.sqrt(distance_squared(point))
end

#distance_squared(point) ⇒ Object



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

def distance_squared(point)
  ((x - point.x).abs ** 2) + ((y - point.y).abs ** 2)
end

#reflect(type = 'origin') ⇒ Object



63
64
65
66
67
# File 'lib/coords/cartesian2d.rb', line 63

def reflect(type = 'origin')
  reflected_point = Cartesian2d.new(x, y)
  reflected_point.reflect!(type)
  reflected_point
end

#reflect!(type = 'origin') ⇒ Object



69
70
71
72
73
74
75
76
77
78
# File 'lib/coords/cartesian2d.rb', line 69

def reflect!(type = 'origin')
  if type == 'line'
    tmp_x = x
    @x = y
    @y = tmp_x
  else
    @x = x * -1 if ['origin', 'y'].include?(type)
    @y = y * -1 if ['origin', 'x'].include?(type)
  end
end

#rotate(theta) ⇒ Object



51
52
53
54
55
# File 'lib/coords/cartesian2d.rb', line 51

def rotate(theta)
  rotated_point = Cartesian2d.new(x, y)
  rotated_point.rotate!(theta)
  rotated_point
end

#rotate!(theta) ⇒ Object



57
58
59
60
61
# File 'lib/coords/cartesian2d.rb', line 57

def rotate!(theta)
  tmp_x = x
  @x = ((x * Math.cos(theta)) - (y * Math.sin(theta))).round(12)
  @y = ((tmp_x * Math.sin(theta)) + (y * Math.cos(theta))).round(12)
end

#to_polarObject



29
30
31
32
33
34
# File 'lib/coords/cartesian2d.rb', line 29

def to_polar
  radius = Math.sqrt((x ** 2) + (y ** 2));
  theta = Math.atan2(y, x);

  Polar.new(radius.round(12), theta.round(12))
end

#to_sObject



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

def to_s
  x.to_s + ',' + y.to_s
end

#translate(x2, y2) ⇒ Object



40
41
42
43
44
# File 'lib/coords/cartesian2d.rb', line 40

def translate(x2, y2)
  translated_point = Cartesian2d.new(x, y)
  translated_point.translate!(x2, y2)
  translated_point
end

#translate!(x2, y2) ⇒ Object



46
47
48
49
# File 'lib/coords/cartesian2d.rb', line 46

def translate!(x2, y2)
  @x += x2
  @y += y2
end

#xObject



9
10
11
# File 'lib/coords/cartesian2d.rb', line 9

def x
  @x
end

#yObject



13
14
15
# File 'lib/coords/cartesian2d.rb', line 13

def y
  @y
end