Vector2D¶
A 2D vector implementation for handling positions, velocities, and other 2D quantities.
Vector2D¶
Methods¶
add()¶
Add two vectors together.sub()¶
Subtract one vector from another.mul()¶
Multiply vector by a scalar.truediv()¶
Divide vector by a scalar.magnitude()¶
Calculate the magnitude (length) of the vector.normalize()¶
Return a normalized copy of this vector.clamp()¶
Clamp the vector's magnitude to a maximum value.dot()¶
Calculate dot product with another vector.Example Usage¶
# Create vectors
pos = Vector2D(100.0, 200.0)
velocity = Vector2D(5.0, -3.0)
# Vector arithmetic
new_pos = pos + velocity * dt
# Normalization
direction = velocity.normalize()
# Magnitude
speed = velocity.magnitude()
# Clamping
clamped_velocity = velocity.clamp(max_speed)
# Dot product
angle_cos = direction.dot(Vector2D(1.0, 0.0))
Best Practices¶
- Performance:
- Cache vector calculations when possible
- Use in-place operations for frequent updates
-
Consider using integers for pixel-perfect positioning
-
Precision:
- Be aware of floating-point precision issues
- Use appropriate epsilon values for comparisons
-
Consider rounding for pixel alignment
-
Memory:
- Reuse vector objects when possible
- Use pooling for frequently created/destroyed vectors
- Clear vector references when no longer needed
Common Issues¶
Precision¶
- Floating-point rounding errors
- Integer vs. float position mismatches
- Accumulating errors in physics calculations
Performance¶
- Unnecessary vector allocations
- Frequent magnitude calculations
- Redundant normalizations
Logic¶
- Division by zero in normalization
- Incorrect vector math operations
- Missing vector cleanup