Skip to content
Martin Prout edited this page Jul 6, 2015 · 18 revisions

Examples

Vec2D v1, v2;

def setup
  noLoop;
  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

Description

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).

Fields

x The x component of the vector

y The y component of the vector

Methods

set Set the components of the vector

from_angle Make a new 2D unit vector from an angle

copy Get a copy of the vector

mag Calculate the magnitude of the vector

+ Adds x, y, and z components to a vector, one vector to another, or two independent vectors

- Subtract x, y, and z components from a vector, one vector from another, or two independent vectors

* Multiply a vector by a scalar

/ Divide a vector by a scalar == equals values

dist Calculate the distance between two points dot Calculate the dot product of two vectors cross Calculate and return the cross product 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 (conditionally if block if given) 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

Constructor

def initialize(x = 0, y = 0)