# 学习OpenGL ES之变换矩阵

### 获取示例代码

3X3矩阵的加法

#### 变换矩阵

``````attribute vec4 position;
attribute vec4 color;

uniform float elapsedTime;
uniform mat4 transform;

varying vec4 fragColor;

void main(void) {
fragColor = color;
gl_Position = transform * position;
}
``````

### 缩放矩阵

``````GLKMatrix4 scaleMatrix = GLKMatrix4MakeScale(sx, sy, sz);
``````

### 旋转矩阵

``````GLKMatrix4 rotateMatrix = GLKMatrix4MakeRotation(M_PI/2 , 0.0, 0.0, 1.0);
``````

M_PI/2是弧度，0.0，0.0，1.0是旋转轴的向量。

### 综合三个矩阵

``````self.transformMatrix = GLKMatrix4Multiply(translateMatrix, rotateMatrix);
self.transformMatrix = GLKMatrix4Multiply(self.transformMatrix, scaleMatrix);
``````

### 代码实现

``````//
//  ViewController.m
//  OpenGLESDemo
//
//  Created by wangyang on 15/8/28.
//

#import "ViewController.h"

@interface ViewController ()
@property (assign, nonatomic) GLKMatrix4 transformMatrix;
@end

@implementation ViewController

self.transformMatrix = GLKMatrix4Identity;
}

#pragma mark - Update Delegate

- (void)update {
[super update];
float varyingFactor = sin(self.elapsedTime);
GLKMatrix4 scaleMatrix = GLKMatrix4MakeScale(varyingFactor, varyingFactor, 1.0);
GLKMatrix4 rotateMatrix = GLKMatrix4MakeRotation(varyingFactor , 0.0, 0.0, 1.0);
GLKMatrix4 translateMatrix = GLKMatrix4MakeTranslation(varyingFactor, 0.0, 0.0);
// transformMatrix = translateMatrix * rotateMatrix * scaleMatrix
// 矩阵会按照从右到左的顺序应用到position上。也就是先缩放（scale）,再旋转（rotate）,最后平移（translate）
// 如果这个顺序反过来，就完全不同了。从线性代数角度来讲，就是矩阵A乘以矩阵B不等于矩阵B乘以矩阵A。
self.transformMatrix = GLKMatrix4Multiply(translateMatrix, rotateMatrix);
self.transformMatrix = GLKMatrix4Multiply(self.transformMatrix, scaleMatrix);
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
[super glkView:view drawInRect:rect];

glUniformMatrix4fv(transformUniformLocation, 1, 0, self.transformMatrix.m);
[self drawTriangle];
}

#pragma mark - Draw Many Things
- (void)drawTriangle {
static GLfloat triangleData[36] = {
0,      0.5f,  0,  1,  0,  0, // x, y, z, r, g, b,每一行存储一个点的信息，位置和颜色
-0.5f,  0.0f,  0,  0,  1,  0,
0.5f,   0.0f,  0,  0,  0,  1,
0,      -0.5f,  0,  1,  0,  0,
-0.5f,  0.0f,  0,  0,  1,  0,
0.5f,   0.0f,  0,  0,  0,  1,
};
[self bindAttribs:triangleData];
glDrawArrays(GL_TRIANGLES, 0, 6);
}

@end

``````

``````attribute vec4 position;
attribute vec4 color;

uniform float elapsedTime;
uniform mat4 transform;

varying vec4 fragColor;

void main(void) {
fragColor = color;
gl_Position = transform * position;
}
``````

OpenGL ES