Vector Addition

Vector addition combines two vectors to produce a single vector that has the combined effect of both. Let's say soldier Alpha has to rendezvous with a drop ship at point C (15, 45) after picking up whatever the droid at point B was guarding. The vector from B to C is (-15, 10), which means he has to go back 15 units in the x direction and continue on 5 units in the y direction. If we add the components of the BC vector to the AB vector, we get a vector that would take us from A to C (see Figure 5-3).

Figure 5-3. Vector addition

To add vector addition to our vector library, we could create a method called add, then call AB.add(BC) to return the result of adding AB and BC together, but it would be more natural if we could simply call AB+BC. Python provides a way for us to do this. By defining a special method called_add_, we can let Python know how to add two instances of Vector2 together.

When Python sees AB+BC, it will attempt to call AB._add_(BC), so we should define_add_to return a new object containing the result of the calculation. This is known as operator overloading. There are similar special methods for all the basic operators, such as_sub_for subtract

(-) and_mul_for multiply (*). Listing 5-10 extends the vector class with an_add_method.

■Caution If you use lists or tuples to store your vectors, don't try to add them together with the + operator. In Python (1, 2)+(3, 4) is not (4, 6); it's actually (1, 2, 3, 4)—which is not a valid 2D vector.

Listing 5-10. Adding the_add_Method to Our Vector2 Class import math class Vector2(object):

@staticmethod def from_points(P1, P2):

def get_magnitude(self):

def normalize(self):

magnitude = self.get_magnitude() self.x /= magnitude self.y /= magnitude

# rhs stands for Right Hand Side def _add_(self, rhs):

AB = Vector2.from_points(A, B) BC = Vector2.from_points(B, C)

AC = Vector2.from_points(A, C) print "Vector AC is", AC

Executing this script produces the following output:

Was this article helpful?

0 0


  • margherita
    How to import vector2 on pygame for python programmer?
    2 months ago

Post a comment