Class: V

Inherits:
Object
  • Object
show all
Defined in:
lib/graphics/v.rb

Overview

Simple and fast 2 dimensional vector

Constant Summary collapse

ZERO =

zero vector

V[0.0, 0.0]
ONE =

one vector

V[1.0, 1.0]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(x, y) ⇒ V

Create a new vector with x & y coordinates.



17
18
19
20
# File 'lib/graphics/v.rb', line 17

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

Instance Attribute Details

#xObject

x coordinate accessors – preferably float



6
7
8
# File 'lib/graphics/v.rb', line 6

def x
  @x
end

#yObject

y coordinate accessors – preferably float



8
9
10
# File 'lib/graphics/v.rb', line 8

def y
  @y
end

Instance Method Details

#*(s) ⇒ Object

Multiply a vector by a scalar, returning a new vector.



52
53
54
# File 'lib/graphics/v.rb', line 52

def * s
  V[x*s, y*s]
end

#+(v) ⇒ Object

Add two vectors, returning a new vector.



31
32
33
# File 'lib/graphics/v.rb', line 31

def + v
  V[x+v.x, y+v.y]
end

#-(v) ⇒ Object

Subtract two vectors, returning a new vector.



38
39
40
# File 'lib/graphics/v.rb', line 38

def - v
  V[x-v.x, y-v.y]
end

#-@Object

Unary negation.



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

def -@
  V[-x, -y]
end

#/(s) ⇒ Object

Divide a vector by a scalar, returning a new vector.



59
60
61
# File 'lib/graphics/v.rb', line 59

def / s
  V[x/s, y/s]
end

#==(other) ⇒ Object

:nodoc:



63
64
65
# File 'lib/graphics/v.rb', line 63

def == other # :nodoc:
  x == other.x && y == other.y
end

#inspectObject Also known as: to_s

:nodoc:



74
75
76
# File 'lib/graphics/v.rb', line 74

def inspect # :nodoc:
  "#{self.class.name}[%.2f, %.2f]" % [x, y]
end

#magnitudeObject

Return the length of the vector from the origin.



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

def magnitude
  @magnitude ||= Math.sqrt(x*x + y*y)
end