原始需求:第一人称行走
第一人称行走的时候,一般是按下WASD键,然后根据相机的方向,然后去驱动player的位移。这里就自然而然的出现一个问题,如何获取相机的方向。
经过查阅相关api得到:Camera.getDirection
这个api的名字非常容易理解,就是获取方向,但是等到使用的时候,就有点困惑了:
(method) Camera.getDirection(localAxis: DeepImmutable<Vector3>): Vector3
Gets the direction of the camera relative to a given local axis.
*@param* `localAxis` — Defines the reference axis to provide a relative direction.
*@returns* — the direction
获取方向就获取方向,还要传一个参数进去,参数名叫什么localAxis,请问这该填啥?
不管了,先翻源码为敬
经过并不深的调用链路,找到了下面的东西:
/**
* Gets the direction of the camera relative to a given local axis into a passed vector.
* @param localAxis Defines the reference axis to provide a relative direction.
* @param result Defines the vector to store the result in
*/
public getDirectionToRef(localAxis: DeepImmutable<Vector3>, result: Vector3): void {
Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
}
实际上就是调用了:
Vector3.TransformNormalToRef
这个函数。
Vector3.TransformNormalToRef 的逻辑是啥
再稍微翻一下源码:
public static TransformNormalFromFloatsToRef<T extends Vector3>(x: number, y: number, z: number, transformation: DeepImmutable<Matrix>, result: T): T {
const m = transformation.m;
result._x = x * m[0] + y * m[4] + z * m[8];
result._y = x * m[1] + y * m[5] + z * m[9];
result._z = x * m[2] + y * m[6] + z * m[10];
result._isDirty = true;
return result;
}
这种格式,我一看便知,因为我有独特的看矩阵乘法的技巧(juejin.cn/post/698916…
上面的链接,我的webgl专栏里关于矩阵乘法已经说的很明白,那么这里,非常明显:
- 就是做了一件事情:将传递进入的
向量
右乘
矩阵
然后返回新的向量。 - 但是:没有考虑translate,从上面的代码来看,没有考虑矩阵的第四行和第四列,也就是说,不考虑translate。
回顾一下传入的矩阵是啥
this.getWorldMatrix()
上面的 this 就是指的这个camera。
那么总结起来就是这个说法:
- 将传入的向量经过 camera 的 worldMatrix ,然后得到返回结果
这个 worldMatrix 应该就是指 MVP 矩阵中的model矩阵了,也就是代表这个 camera 的旋转和位移, 为什么没有拉伸呢? (谁会去拉伸一个camera,camera本身又不用渲染。。。)
结论
传什么向量进去,就是获取这个向量经过camera的worldMatrix转换之后的向量。(忽略位移)
那么自然的,忽略了位移,出来的结果肯定会保留 旋转信息了,于是肯定也包含了方向信息。
问题的答案
那么到底传什么向量进去,才能得到我们想要的结果呢,也就是得到camera的方向向量。
答:去看一下camera初始化的时候的朝向吧。
经过检测,camera初始化的时候的朝向就是 (0, 0, 1)。好了, 答案如下:
const cameraDir = camera.getDirection(new Vector3(0, 0, 1));
免责声明
以上个人看法,如有错误,纯属搞笑。