Matrix Components

It is possible to access the components of a matrix individually (see Figure 9-2). You can access individual values using the index operator ([]), which takes the row and column of the value in the matrix you are interested in. For example, matrix[3, 1] returns the value at row 3, column 1 and matrix[3, 1] = 2.0 would set that same value to 2.0. This value is actually the y component of the translation part of the matrix, so changing it would alter the height of an object over the ground.

Figure 9-2. Matrix components

Figure 9-2. Matrix components

Individual rows of the matrix can be extracted by calling the get_row method, which returns the row as a tuple of four values. For example, matrix.get_row(0) returns row zero (top row, x axis), and matrix.get_row(3) returns the last row. There is also an equivalent set_row method, which takes the index of the row you want to set, and a sequence of up to four values to copy into the row. As with most methods of the Matrix44 class, get_row and set_row work with Vector3 objects as well as the built-in types.

The Matrix44 class also contains a number of attributes you can use to retrieve rows, which can be more intuitive than using the row index. For instance, rather than doing m. get_row(3) to retrieve the translation part of a matrix, you can use the attribute m.translate, which has the same effect. You can also replace m.set_row(3, (1, 2, 3)) with m.translate = (1, 2, 3)— both will set the first three values ofrow 3 to (1, 2, 3). Table 9-1 lists the attributes you can use to access rows in a matrix.

Table 9-1. Row Attributes for Matrix44 Objects

Matrix Attribute Alias x_axis Row 0

y_axis Row 1

z_axis Row 2

right Row 0

up Row 1

forward Row 2

translate Row 3

You can also get and set the columns of a matrix with get_column and set_column, which work in the same way as the row methods. They are perhaps less useful, because columns don't give you as much relevant information as the rows do. One use for get_column is to check that the right column is (0, 0, 0, 1), because anything else may indicate an error in your code. Listing 9-1 is an example of how to check a matrix for validity. It uses Python's assert keyword to check column 3 of the matrix. If the third column is (0, 0, 0, 1), then nothing happens; otherwise, Python will throw an AssertionError. You should never catch these types of exceptions; they are Python's way of telling you that something is wrong with your code and that you should investigate the problem.

Was this article helpful?

0 0

Post a comment