# 具体解释MVP矩阵之ViewMatrix

### 矩阵推导

ViewMatrix用于直接将World坐标系下的坐标转换到Camera坐标系下。已知相机的坐标系。还有相机在世界空间下的坐标.就能够求出ViewMatrix。以下进行具体推导。

C = TR

R^(-1)比較难求出，这里用到了正交基一些知识，能够參考下碰撞检測之Ray-Cylinder检測前面关于正交基的部分。

### Look At Camera

```Matrix4x4 LookAt(const Vector3& eye, const Vector3& target, const Vector3& up)
{
Vector3 z((eye - target).normalized());
Vector3 x((Vector3::Cross(z, up).normalized()));
Vector3 y(Vector3::Cross(x, z));

Matrix4x4 result;

result[0] = x.x;
result[4] = x.y;
result[8] = x.z;
result[12] = -Vector3::Dot(x, eye);

result[1] = y.x;
result[5] = y.y;
result[9] = y.z;
result[13] = -Vector3::Dot(y, eye);

result[2] = z.x;
result[6] = z.y;
result[10] = z.z;
result[14] = -Vector3::Dot(z, eye);

result[3] = result[7] = result[11] = 0.0f;
result[15] = 1.0f;
return result;
}```

```//C++
qDebug() << Transform::LookAt(Vector3(1, 2, 3), Vector3(0, 10, 0), Vector3::up);```

```//Unity
transform.position = new Vector3(1, 2, 3);
transform.LookAt(new Vector3(0, 10, 0), Vector3.up);
Debug.Log(Camera.main.worldToCameraMatrix);```

（貌似Unity中的Transform.LookAt函数是直接改动的Camera的Rotation？）

### FPS Camera

```Matrix4x4 Transform::FPSView(const Vector3& eye, Quaternion rotation)
{
Matrix4x4 rotMatrix = rotation.GetRotMatrix().transpose();
Vector3 x(rotMatrix[0], rotMatrix[4], rotMatrix[8]);
Vector3 y(rotMatrix[1], rotMatrix[5], rotMatrix[9]);
Vector3 z(-rotMatrix[2], -rotMatrix[6], -rotMatrix[10]);

Matrix4x4 result;

result[0] = x.x;
result[4] = x.y;
result[8] = x.z;
result[12] = -Vector3::Dot(x, eye);

result[1] = y.x;
result[5] = y.y;
result[9] = y.z;
result[13] = -Vector3::Dot(y, eye);

result[2] = z.x;
result[6] = z.y;
result[10] = z.z;
result[14] = -Vector3::Dot(z, eye);

result[3] = result[7] = result[11] = 0.0f;
result[15] = 1.0f;
return result;
}```

```//C++
qDebug() << Transform::FPSView(Vector3(1,2,3), Quaternion::Euler(30, 45, 60));```

```//unity
transform.position = new Vector3(1, 2, 3);
transform.rotation = Quaternion.Euler(30, 45, 60);
Debug.Log(Camera.main.worldToCameraMatrix);```

### 參考

Understanding the View Matrix - http://www.3dgep.com/understanding-the-view-matrix/

Tutorial 3 : Matrices - http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/

OpenGL Transformation - http://www.songho.ca/opengl/gl_transform.html

## Cg入门10：Vertex Shader - 几何变换 —MVP矩阵变换

Unity内建矩阵类型: M:世界矩阵 V:摄像机矩阵 P:投影矩阵 T :矩阵的转置 IT : 转置的的逆 _Object2World: 模型到世界矩阵 _World2Object:世界到模型矩阵 MVP 矩阵变换:Shader Demo MVP 转置变换:C# demo Matrix4x4 mvp = Camera.main .projectionMatrix * Camera.main .worldToCameraMatrix * transform .localToWorldMatrix

## python小白之矩阵matrix笔记(updating)

Matrix #python学习之矩阵matrix 2018.4.18 # -*- coding: UTF-8 -*- from numpy import * import numpy as np import math a=np.matrix('1 2 7;3 4 8;5 6 9')#矩阵的换行必须使用分号隔开,内部数据必须为字符串形式,元素之间必须以空格隔开 print(np.matrix([[1,2],[3,4]])) m=np.asmatrix(a)#将输入的a解释为矩阵m,并修改m中某