实现高效的Vector / Point类的最佳方法是什么(甚至更好:是否有一个),可以在
Python 2.7和3.x中使用?
我找到了the blender-mathutils,但它们似乎只支持Python 3.x.然后是this Vector class,使用numpy,但它只是一个3D矢量.使用具有静态属性(x和y)的像kivy’s vector class(sourcecode)的Vector的列表似乎也很奇怪. (有所有这些列表方法.)
目前我正在使用一个扩展了namedtuple的类(如下所示),但这样做的缺点是无法更改坐标.我认为当成千上万的对象移动并且每次都创建一个新的(矢量)元组时,这可能会成为一个性能问题. (对?)
class Vector2D(namedtuple('Vector2D', ('x', 'y'))):
__slots__ = ()
def __abs__(self):
return type(self)(abs(self.x), abs(self.y))
def __int__(self):
return type(self)(int(self.x), int(self.y))
def __add__(self, other):
return type(self)(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return type(self)(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return type(self)(self.x * other, self.y * other)
def __div__(self, other):
return type(self)(self.x / other, self.y / other)
def dot_product(self, other):
return self.x * other.x + self.y * other.y
def distance_to(self, other):
""" uses the Euclidean norm to calculate the distance """
return hypot((self.x - other.x), (self.y - other.y))
编辑:我做了一些测试,似乎使用numpy.array或numpy.ndarray作为矢量太慢了. (例如,获取一个项目需要几乎两倍的时间,更不用说创建一个数组.我认为它更适合于对大量项目进行计算.)
所以,我正在寻找一个轻量级的矢量类,它具有固定数量的字段(在我的例子中只有x和y),可以用于游戏. (如果已经有一个经过充分测试的车轮,我不想重新发明轮子.)