官术网_书友最值得收藏!

Translation

Translation is stored as a three-dimensional vector inside a 4 X 4 matrix. The translation component of the matrix describes how much to move an object on each axis. Because we decided to use Row Major matrices, translation is stored in elements 41, 42, and 43 of the matrix:

Translation

Getting Ready

We're going to implement three functions: one to retrieve the translation already stored inside a 4 X 4 matrix, one to return a translation matrix given x, y, and z components, and one to return a translation matrix given the same x, y, and z components packed inside a vec3. When building any type of matrix, we start with the identity matrix and modify elements. We do this because the identity matrix has no effect on multiplication. The unused elements of a translation matrix should not affect rotation or scale; therefore we leave the first three rows the same as the identity matrix.

How to do it…

Follow these steps to set and retrieve the translation of a matrix:

  1. Add the declaration for all of the translation functions to matrices.h:
    mat4 Translation(float x, float y, float z);
    mat4 Translation(const vec3& pos);
    vec3 GetTranslation(const mat4& mat);
  2. Implement the functions that create 4 X 4 matrices in matrices.cpp. Because this matrix has no rotation, we start with the identity matrix and fill in only the elements related to translation:
    mat4 Translation(float x, float y, float z) {
       return mat4(
          1.0f, 0.0f, 0.0f, 0.0f,
          0.0f, 1.0f, 0.0f, 0.0f,
          0.0f, 0.0f, 1.0f, 0.0f,
          x,    y,    z,    1.0f
       );
    }
    
    mat4 Translation(const vec3& pos) {
       return mat4(
          1.0f, 0.0f, 0.0f, 0.0f,
          0.0f, 1.0f, 0.0f, 0.0f,
          0.0f, 0.0f, 1.0f, 0.0f,
          pos.x,pos.y,pos.z,1.0f
       );
    }
  3. Implement the function that retrieves the translation component of a 4 X 4 matrix in matrices.cpp:
    vec3 GetTranslation(const mat4& mat) {
       return vec3(mat._41, mat._42, mat._43);
    }

How it works…

Both Translation functions return a new 4 X 4 matrix. This matrix is the identity matrix, with translation information stored in elements 41, 42, and 43. We start off with the identity matrix because we don't want the translation matrix to affect rotation or scale. The GetTranslation function just needs to return elements 41, 42, and 43 packed into a vec3 structure.

主站蜘蛛池模板: 墨竹工卡县| 且末县| 瑞金市| 铁岭县| 安泽县| 兴化市| 四平市| 张家川| 易门县| 大余县| 南丰县| 抚松县| 开江县| 朝阳市| 义马市| 瓮安县| 社会| 喀喇| 蚌埠市| 五寨县| 聂荣县| 彭水| 汉源县| 湾仔区| 荥阳市| 兰溪市| 宿州市| 平邑县| 偏关县| 临江市| 文安县| 卓尼县| 望城县| 曲阳县| 宜昌市| 浙江省| 佛教| 黑水县| 郯城县| 开阳县| 日土县|