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

RE: [pygame] 2D Vector Class



I'm a little lost on this... Someone wants a 2D vector class?

I use the following I built after wrestling with the NeHe particle tutorial:

class Vector2D(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, v):
        return Vector2D(float(self.x + v.x), float(self.y + v.y))
        
    def __sub__(self, v):
        return Vector2D(float(self.x - v.x), float(self.y - v.y))

class Vector3D(Vector2D):
    def __init__(self, x, y, z):
        super(Vector3D, self).__init__(x, y)
        self.z = z

    def __add__(self, v):
        return Vector3D(float(self.x + v.x), float(self.y + v.y),
float(self.z + v.z))
        
    def __sub__(self, v):
        return Vector3D(float(self.x - v.x), float(self.y - v.y),
float(self.z - v.z))

---snip---

v1 = Vector3D(1.0, 1.0, 1.0)
v2 = Vector3D(2.0, 2.0, 2.0)
v3 = v1 - v2

print v3.x, v3.y, v3.z
>>> -1.0, -1.0, -1.0

---snip---

These allow me to add/subtract instances of a Vector3D class and get a
Vector3D class in return. I only have add and subtract on these methods, but
I could easily extend them by using the information at
http://docs.python.org/ref/customization.html and
http://docs.python.org/lib/module-operator.html to add more math methods.

As I say, I'm a little lost and confused... I put this down to Delta/Atlanta
airport yesterday and a funtastic trip from Oregon to Florida. Ignore me.

-----Original Message-----
From: owner-pygame-users@xxxxxxxx [mailto:owner-pygame-users@xxxxxxxx]On
Behalf Of Greg Ewing
Sent: Wednesday, May 16, 2007 23:41
To: pygame-users@xxxxxxxx
Subject: Re: [pygame] 2D Vector Class


Ulf Ekström wrote:

> > That [complex number trick] seems very smart, and I imagine it is very
fast...
> 
> Yes, and you get fast rotations with just a multiply.

Only for 2D, though... unless we can persuade Guido
to put quaternions in the core... :-)

-- 
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | Carpe post meridiem!          	  |
Christchurch, New Zealand	   | (I'm not a morning person.)          |
greg.ewing@xxxxxxxxxxxxxxxx	   +--------------------------------------+




CONFIDENTIAL NOTICE: This email including any attachments, contains 
confidential information belonging to the sender. It may also be 
privileged or otherwise protected by work product immunity or other 
legal rules. This information is intended only for the use of the 
individual or entity named above.  If you are not the intended 
recipient, you are hereby notified that any disclosure, copying, 
distribution or the taking of any action in reliance on the contents 
of this emailed information is strictly prohibited.  If you have 
received this email in error, please immediately notify us by 
reply email of the error and then delete this email immediately.