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

[pygame] 2D vector class



Ok, I learned a lot when I asked the question about Rects and my
confusion about their bottom/left overlapping.  So, here goes another on
2D vectors...

I've got 2 simple games roughed out (about 600 lines each) with about
2000 lines worth of shared modules I've written.  I have a somewhat full
featured 2D vector class (supports adding, subtracting, scaling,
rotation, normalizing, angle between, etc. that I use in both heavily to
represent points, velocities, etc.  After using it for awhile, I've
wondered how others have approached creating a 2D vector class.  Here's
my "philosophical" questions, as the class I have works well, but I want
to know how to make it better.  My main goals are to keep it simple, let
it interface cleanly with Pygame's use of tuples of 2 ints for 2D
points, not be specifically tied to Pygame, and have it not be a
performance hog.

So, here's the issues that I'd love to hear feedback on:

#1 - Do you store the vector components internally as self.x and self.y
or as a tuple?  Or subclass the vector class from a tuple?  If you use
self.x and self.y, what is an efficient way to pass this as a tuple to
pygame functions?

#2 - Do you store the values as ints (making it easier to pass to
Pygame) or floats (more accurate vector math, but need to cast to int
before passing to pygame functions that require a tuple of ints?).  Or
do you not even care and just let duck-typing do it stuff?

So, after using my 2D vect class for awhile, I wasn't sure if I had
taken the best approach originally.  Currently, my vector class stores
floats in self.x and self.y and I have 2 methods for returning tuples as
follows:
		
def AsTuple(self):
	return((self.x, self.y))

def AsIntTuple(self):
	'''Cast values to int. Useful for Pygame'''
	return((int(self.x), int(self.y)))

The other motivation in sending this email out is I'd like to submit a
semi-simple particle system module I have to the Cookbook, but it relies
on my 2d vector class.  So, I wanted to tighten up my vector class and
submit both it  and the particle system modules.  Hopefully, then, other
cookbook entries could use this vector class (and improve upon it,
please!).  Lofty goals?  Maybe, but gotta start somewhere, right?

Thanks, all for reading this far!

-Scott