## Vector Multiplication and Division

It is also possible to multiply (or divide) a vector by a scalar (a number), which has the effect of changing the length of the vector. Simply multiply or divide each component by the scalar value. Listing 5-13 adds two methods to our Vector2 class to implement multiply and divide capabilities.

Listing 5-13. Vector Multiplication and Division def _mul_(self, scalar):

return Vector2(self.x * scalar, self.y * scalar)

return Vector2(self.x / scalar, self.y / scalar)

If you multiply any vector by 2.0, it will double in size; if you divide a vector by 2.0 (or multiply by 0.5), it will halve the size. Multiplying a vector by a number greater than 0 will result in a vector that points in the same direction, but if you were to multiply by a number less than 0, the resulting vector would be "flipped" and point in the opposite direction (see Figure 5-4). ■Note Multiplying a vector by another vector is also possible, but it isn't used very often in games and you will probably never need it.

So how might soldier Alpha use vector multiplication—or more accurately, how would the game programmer use it? Vector multiplication is useful to break up a vector into smaller steps based on time. If we know Alpha can cover the distance from A to B in 10 seconds, we can calculate the coordinates where Alpha will be after every second by using a little vector code. Listing 5-14 shows how you might do this using the Vector2 class.

Listing 5-14. Calculating Positions

A = (10.0, 20.0) B = (30.0, 35.0) AB = Vector2.from_points(A, B) step = AB * .1

position = Vector2(A.x, A.y) for n in range(l0): position += step print position

This produces the following output:

 (12. 0, 21 5) (14. 0, 23 0) (16. 0, 24 5) 1 . 0, 26 0) (20. 0, 27 5) (22. 0, 29 0) (24. 0, 30 5) (26. 0, 32 0) (28. 0, 33 5) (30. 0, 35 0)

After calculating a vector between points A and B, Listing 5-14 creates a vector step that is one-tenth of the AB vector. The code inside the loop adds this value to position, which is another vector we will use to store Alpha's current location. We do this ten times, once for each second of Alpha's journey, printing out the current position vector as we go. Eventually alter ten iterations we reach point B, safe and sound! If you were to take the output and plot the points, you would see that they form a perfect straight line from A to B.

Calculating intermediate positions like this is essential when moving between two points. You can also use vectors to calculate movement under gravity, external forces, and friction to create various kinds of realistic motion.