-
Notifications
You must be signed in to change notification settings - Fork 9
Vec2D
attr_reader :v1, :v2
def setup
no_loop
@v1 = Vec2D.new(40, 20)
@v2 = Vec2D.new(25, 50)
end
def draw
ellipse(v1.x, v1.y, 12, 12)
ellipse(v2.x, v2.y, 12, 12)
v2.add(v1)
ellipse(v2.x, v2.y, 24, 24)
end
def settings
size 100, 100
end
A class to describe a two dimensional vector, specifically a Euclidean (also known as geometric) vector. A vector is an entity that has both magnitude and direction. The datatype, however, stores the components of the vector (x, y). The magnitude and direction can be accessed via the methods mag and heading.
In many of the JRubyArt examples, you will see Vec2D used to describe a position, velocity, or acceleration. For example, if you consider a rectangle moving across the screen, at any given instant it has a position (a vector that points from the origin to its location), a velocity (the rate at which the object's position changes per time unit, expressed as a vector), and acceleration (the rate at which the object's velocity changes per time unit, expressed as a vector). Since vectors represent groupings of values, we cannot simply use traditional addition/multiplication/etc. Instead, we do some vector
math, which is made easy by the methods inside the Vec2D class (+, -, /, *
are used nevertheless).
x
The x component of the vector
y
The y component of the vector
set
Set the components of the vector
from_angle
Make a new 2D unit vector from an angle
copy
, dup
Returns a copy of the vector
mag
Calculate the magnitude of the vector
+
Adds x, and y components to a vector, one vector to another
-
Subtract x, and y components from a vector, one vector to another
*
Multiply a vector by a scalar
/
Divide a vector by a scalar
==
equals values
eqls?
equals values
equals
identity equals
dist
Calculate the distance between two points
dot
Calculate the dot product of two vectors
cross
Calculate and return the cross product of two vectors
normalize
Returns copy of vector normalized to a length of 1
normalize!
Normalize the vector to a length of 1
limit
Limit the magnitude of the vector
set_mag
set the vector magnitude to a given scalar (accepts an optional block
, which if given should evaluate to a boolean
to allow conditional setting to eg max velocity
)
heading
Returns the angle of rotation for this vector
rotate
Return a copy of the vector rotated by an angle
rotate!
Rotate the vector by an angle
lerp
Return a new vector a linear interpolation of a vector to another vector
lerp!
Linear interpolate the vector to another vector
angle_between
Calculate and return the angle between two vectors
to_a
Returns a representation of the vector as an array of Float
inspect
Returns to_s
to_s
Returns a representation of the vector as a string
def initialize(x = 0, y = 0)