The vec2d class is a powerful 2D vector implementation that supports vector and scalar operations, along with high-level geometric functions. Itβs used throughout Serenity Valley for positioning, movement, and mathematical calculations.
v = vec2d(3, 4)# Get length (magnitude)length = v.get_length() # Returns 5.0length = v.length # Property access# Get squared length (faster, no sqrt)length_sqrd = v.get_length_sqrd() # Returns 25# Set length (scales the vector)v.length = 10 # Now vec2d(6, 8)# Normalize and get original lengthoriginal_length = v.normalize_return_length()# v is now unit vector, returns original length
Use get_length_sqrd() when comparing distances to avoid expensive square root calculations.
Work with vector angles and rotation.
v = vec2d(1, 0)# Get angle in degreesangle = v.get_angle() # Returns 0angle = v.angle # Property access# Set angle (rotates to specified angle)v.angle = 90 # Now points upward# Rotate by angle (in-place)v.rotate(45) # Rotates 45 degrees# Get rotated copy (non-destructive)v2 = v.rotated(90) # v unchanged, v2 is rotated# Get angle between two vectorsv1 = vec2d(1, 0)v2 = vec2d(0, 1)angle = v1.get_angle_between(v2) # Returns 90
Create unit vectors (length = 1).
v = vec2d(3, 4) # length = 5# Get normalized copyunit = v.normalized() # vec2d(0.6, 0.8)# Original v is unchanged# Normalize and return original lengthoriginal = v.normalize_return_length()# v is now normalized, returns 5.0
Normalized vectors are useful for direction calculations while preserving the original magnitude separately.
# Get direction from point A to point Bpoint_a = vec2d(100, 100)point_b = vec2d(200, 150)direction = (point_b - point_a).normalized()speed = 5velocity = direction * speed
# Check if two objects are closeplayer_pos = vec2d(100, 100)enemy_pos = vec2d(150, 150)# Use squared distance to avoid sqrtif player_pos.get_dist_sqrd(enemy_pos) < 50**2: print("Enemy is within range!")