feat: add vec class
This commit is contained in:
		
							
								
								
									
										57
									
								
								src/vec.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										57
									
								
								src/vec.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,57 @@ | |||||||
|  | from __future__ import annotations | ||||||
|  |  | ||||||
|  | from math import sqrt | ||||||
|  |  | ||||||
|  |  | ||||||
|  | class Vec: | ||||||
|  |     def __init__(self, x: float = 0, y: float = 0) -> None: | ||||||
|  |         self.x: float = x | ||||||
|  |         self.y: float = y | ||||||
|  |  | ||||||
|  |     def __add__(self, other: float | Vec) -> Vec: | ||||||
|  |         if isinstance(other, Vec): | ||||||
|  |             return Vec(self.x + other.x, self.y + other.y) | ||||||
|  |         return Vec(self.x + other, self.y + other) | ||||||
|  |  | ||||||
|  |     def __sub__(self, other: float | Vec) -> Vec: | ||||||
|  |         if isinstance(other, Vec): | ||||||
|  |             return Vec(self.x - other.x, self.y - other.y) | ||||||
|  |         return Vec(self.x - other, self.y - other) | ||||||
|  |  | ||||||
|  |     def __mul__(self, value: float) -> Vec: | ||||||
|  |         return Vec(self.x * value, self.y * value) | ||||||
|  |  | ||||||
|  |     def __truediv__(self, value: float) -> Vec: | ||||||
|  |         return Vec(self.x / value, self.y / value) | ||||||
|  |  | ||||||
|  |     def dot(self, other: Vec) -> float: | ||||||
|  |         return self.x * other.x + self.y * other.y | ||||||
|  |  | ||||||
|  |     def mag(self) -> float: | ||||||
|  |         return sqrt(self.mag2()) | ||||||
|  |  | ||||||
|  |     def mag2(self) -> float: | ||||||
|  |         return self.dot(self) | ||||||
|  |  | ||||||
|  |     def cross(self, other: Vec) -> float: | ||||||
|  |         return self.x * other.y - self.y * other.x | ||||||
|  |  | ||||||
|  |     @property | ||||||
|  |     def normalized(self) -> Vec: | ||||||
|  |         mag: float = self.mag() | ||||||
|  |         if mag == 0: | ||||||
|  |             return Vec() | ||||||
|  |         return self / mag | ||||||
|  |  | ||||||
|  |     def __len__(self) -> int: | ||||||
|  |         return 2 | ||||||
|  |  | ||||||
|  |     def __getitem__(self, item): | ||||||
|  |         return [self.x, self.y][item] | ||||||
|  |  | ||||||
|  |     @property | ||||||
|  |     def perp(self) -> Vec: | ||||||
|  |         return Vec(-self.y, self.x) | ||||||
|  |  | ||||||
|  |     def __repr__(self) -> str: | ||||||
|  |         return f"Vec({self.x}, {self.y})" | ||||||
		Reference in New Issue
	
	Block a user