[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] 2D Vector Class



I implemented one but then found it to be a bit of a performance hotspot. I switched to using complex numbers instead which work wonderfully. I added a small amount of abstraction around them so that other code could remain ignorant of that implementation detail.

Here's an excerpt from my vector.py module (no external dependancies):

import math
import cmath

vector2 = complex

length = abs

def to_tuple(vector):
	return (vector.real, vector.imag)

def radians(vector):
	return math.atan2(vector.imag, vector.real)

def unit(radians):
	return cmath.exp(radians * 1j)

def normal(vector):
	L = length(vector)
	if L == 0:
		return vector2()
	else:
		return vector / L

def clamp(vector, max_length):
	L = length(vector)
	if L > max_length:
		return vector * (max_length / L)
	else:
		return vector

def distance(vector1, vector2):
	return length(vector1 - vector2)

hth,

-Casey

On May 16, 2007, at 12:25 PM, John Krukoff wrote:

So, I’ve been working on a simple physics system, and have gotten to the point where passing around a tuple just isn’t cutting it. Can anybody suggest a good 2D vector implementation?


So far I”ve found this one on the wiki (anybody know who wrote this?):

http://www.pygame.org/wiki/2DVectorClass


And this one as part of the game objects library on Will McGugan’s blog, which also comes with a standalone matrix implementation:


http://www.willmcgugan.com/game-objects/


I’d guess that numeric/numpy is probably a good way to do this too, but I’ve been trying to avoid pulling that in as a dependency.



---------

John Krukoff

helot@xxxxxxxxxxx