Skip to content

Instantly share code, notes, and snippets.

@whitehat101
Last active April 13, 2016 00:08
Show Gist options
  • Save whitehat101/470ea1c081d81a0e26f273c546b84d5b to your computer and use it in GitHub Desktop.
Save whitehat101/470ea1c081d81a0e26f273c546b84d5b to your computer and use it in GitHub Desktop.
Vector2D
class Vector2D
include Math
attr_accessor :x, :y
def self.magnitude_angle magnitude, angle
x = magnitude * cos(angle*PI/180)
y = magnitude * sin(angle*PI/180)
new x, y
end
def initialize x, y
@x = x; @y = y
end
def magnitude
sqrt x*x + y*y
end
def angle
rad = atan y/x
rad += PI if x < 0
rad += 2*PI if rad < 0
rad*180/PI
end
def + other
self.class.new x+other.x, y+other.y
end
def - other
self.class.new x-other.x, y-other.y
end
def -@
self.class.new -x, -y
end
def +@
self
end
def inspect
"<Vector2D x:#{x}, y:#{y} mag:#{magnitude} angle:#{angle}>"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment