Monday, March 2, 2009

Ruby Vector2D

A 2D Vector for Ruby. This is for the Koch snowflake and future 2D examples. Feel free to let me know how I can improve it, or where I can find a good third-party implementation.

Writing geometry classes has been one of my biggest frustrations because of the different implementations, or lack thereof, in the various graphics packages. As a result of this, my first instinct when picking up a new framework is figuring out what geometry is supported and the operations that are available.

A good geometry class for points, vectors, lines, shapes, etc., can save you a lot of headache trying to remember how to do a certain geometrical operation, and focus instead on putting these operations together.


# Use this so glVertex works.
require 'opengl'

class Vector
attr_accessor :x, :y;

def initialize(x,y)
self.x = x
self.y = y
end

def gl_vertex
GL::Vertex2f(x,y)
end

def normal
Vector.new(-@y,@x)
end

def normalize
before_length = length
return if before_length == 0
@x /= before_length
@y /= before_length
end

def length
return Math.sqrt(@x*@x + @y*@y)
end

def reverse
@x = -@x
@y = -@y
end

def add_vector(v)
@x += v.x
@y += v.y
end

def sub_vector(v)
@x -= v.x
@y -= v.y
end

def multiply(scalar)
@x *= scalar
@y *= scalar
end

def divide(scalar)
@x = @x / (1.0 * scalar)
@y = @y / (1.0 * scalar)
end

def Vector.copy(p)
return Vector.new(p.x,p.y)
end

def Vector.between(p1,p2)
between = Vector.new(p2.x,p2.y)
between.sub_vector(p1)
return between
end

def to_s
"#{x}, #{y}"
end

def Vector.midpoint(p1, p2)
midpoint = Vector.new(p1.x,p1.y)
midpoint.add_vector(p2)
midpoint.divide(2.0)
return midpoint
end
end

No comments:

Post a Comment