Vector2

A 2D vector with x and y components.

Vectors represent directions and displacements in the layout plane. They are used for translations, port directions, and geometric calculations. Vectors are immutable -- all methods return new Vector2 instances.

v = Vector2(3, 4)
v.length()      # 5.0
v.normalize()   # Vector2(0.6, 0.8)

# Unit vectors and angle construction
right = Vector2.unit_x()            # Vector2(1, 0)
diagonal = Vector2.from_angle(45)   # Vector2(0.707..., 0.707...)

Attributes

attributexfloat

X component.

attributeyfloat

Y component.

Static methods

funcunit_x() -> Vector2

Return the unit vector along the X axis: Vector2(1, 0).

Returns

Vector2
funcunit_y() -> Vector2

Return the unit vector along the Y axis: Vector2(0, 1).

Returns

Vector2
funcfrom_angle(angle_deg) -> Vector2

Create a unit vector from an angle in degrees. 0 degrees points along +X, 90 degrees points along +Y.

paramangle_degfloat

Angle in degrees (counter-clockwise from +X).

Returns

Vector2

A unit vector pointing in the given direction.

Methods

func__init__(x=0.0, y=0.0) -> None

Create a new vector.

paramxfloat
= 0.0

X component.

paramyfloat
= 0.0

Y component.

Returns

None
funclength() -> float

Return the Euclidean length (magnitude) of the vector.

Returns

float
funcnormalize() -> Vector2

Return a unit vector in the same direction. The original vector must be non-zero.

Returns

Vector2

A new vector with length 1.

funcdot(other) -> float

Compute the dot product with another vector.

paramotherVector2

The other vector.

Returns

float

The scalar dot product.

funcperpendicular() -> Vector2

Return a vector perpendicular to this one (rotated 90 degrees counter-clockwise).

Returns

Vector2
funcrotate(angle_deg) -> Vector2

Rotate the vector by the given angle.

paramangle_degfloat

Rotation angle in degrees (counter-clockwise).

Returns

Vector2

A new rotated vector.

Supported operations

Addition: v1 + v2 returns a new Vector2 that is the component-wise sum.

Vector2(1, 2) + Vector2(3, 4)  # Vector2(4, 6)

Subtraction: v1 - v2 returns a new Vector2 that is the component-wise difference.

Vector2(5, 7) - Vector2(1, 2)  # Vector2(4, 5)

Scalar multiplication: v * scalar or scalar * v scales both components.

Vector2(3, 4) * 2    # Vector2(6, 8)
2 * Vector2(3, 4)    # Vector2(6, 8)

Negation: -v returns a vector pointing in the opposite direction.

-Vector2(3, -4)  # Vector2(-3, 4)

On this page