Skip to content

Instantly share code, notes, and snippets.

@egdelwonk
Last active June 30, 2020 08:43
Show Gist options
  • Save egdelwonk/6878828 to your computer and use it in GitHub Desktop.
Save egdelwonk/6878828 to your computer and use it in GitHub Desktop.
Python implementation of vector class from 'Math for Game Developers Video Series by Jorge Rodriguez' http://www.youtube.com/watch?v=DxmGxkhhluU&list=PLW3Zl3wyJwWOpdhYedlD-yCB7WQoHf-My
import math
class Vector(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __add__(self, vector):
return Vector(vector.x + self.x, vector.y + self.y)
def __sub__(self, vector):
return Vector(self.x - vector.x, self.y - vector.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __div__(self, scalar):
return Vector(self.x / scalar, self.y / scalar)
@property
def length(self):
return math.hypot(self.x, self.y)
@property
def length_sqr(self):
return self.x * self.x + self.y* self.y
def normalized(self):
return Vector(self.x / self.length, self.y / self.length)
'''
Python implementation of vector class from 'Math for Game Developers Video Series by Jorge Rodriguez'
http://www.youtube.com/watch?v=DxmGxkhhluU&list=PLW3Zl3wyJwWOpdhYedlD-yCB7WQoHf-My
'''
p = Vector(0, -1)
i = Vector(1, 1)
c = Vector(2, -1)
cp = p - c
ip = p - i
print 'cp length: {}, squared: {}'.format(cp.length, cp.length_sqr)
print 'ip length: {}, squared: {}'.format(ip.length, ip.length_sqr)
cp length: 2.0, squared: 4.0
ip length: 2.2360679775, squared: 5.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment