RoboidControl-python/Direction.py
2024-12-21 14:30:07 +01:00

44 lines
1.3 KiB
Python

import math
class Direction:
def __init__(self, horizontal=0, vertical=0):
self.horizontal = horizontal
self.vertical = vertical
def __add__(self, other):
return Direction(self.horizontal + other.x, self.vertical + other.y)
def __sub__(self, other):
return Direction(self.horizontal - other.x, self.vertical - other.y)
def __mul__(self, scalar):
return Direction(self.horizontal * scalar, self.vertical * scalar)
def __truediv__(self, scalar):
if scalar != 0:
return Direction(self.horizontal / scalar, self.vertical / scalar)
else:
raise ValueError("Cannot divide by zero")
def magnitude(self):
return math.sqrt(self.horizontal**2 + self.vertical**2)
def normalize(self):
mag = self.magnitude()
if mag != 0:
return Direction(self.horizontal / mag, self.vertical / mag)
else:
return Direction(0, 0)
def dot(self, other):
return self.horizontal * other.x + self.vertical * other.y
def __repr__(self):
return f"Direction(x={self.horizontal}, y={self.vertical})"
Direction.forward = Direction(0, 0)
Direction.backward = Direction(-180, 0)
Direction.up = Direction(0, 90)
Direction.down = Direction(0, -90)
Direction.left = Direction(-90, 0)
Direction.right = Direction(90, 0)