我目前正在扩展我的 3D 引擎以获得更好的实体系统,其中包括相机。这使我可以将相机放入也可能在另一个实体中的父实体中(等等......)。
--Entity
----Entity
------相机
现在我想设置相机的外观方向,我正在使用以下方法执行此操作,该方法也用于设置实体的外观:
public void LookAt(Vector3 target, Vector3 up)
{
Matrix4x4 oldValue = _Matrix;
_Matrix = Matrix4x4.LookAt(_Position, target, up) * Matrix4x4.Scale(_Scale);
Vector3 p, s;
Quaternion r;
Quaternion oldRotation = _Rotation;
_Matrix.Decompose(out p, out s, out r);
_Rotation = r;
// Update dependency properties
ForceUpdate(RotationDeclaration, _Rotation, oldRotation);
ForceUpdate(MatrixDeclaration, _Matrix, oldValue);
}
但是该代码仅适用于相机而不适用于其他实体,当将此方法用于其他实体时,对象正在其位置旋转(实体位于根节点,因此它没有父节点)。矩阵的查看方法如下所示:
public static Matrix4x4 LookAt(Vector3 position, Vector3 target, Vector3 up)
{
// Calculate and normalize forward vector
Vector3 forward = position - target;
forward.Normalize();
// Calculate and normalie side vector ( side = forward x up )
Vector3 side = Vector3.Cross(up, forward);
side.Normalize();
// Recompute up as: up = side x forward
up = Vector3.Cross(forward, side);
up.Normalize();
//------------------
Matrix4x4 result = new Matrix4x4(false)
{
M11 = side.X,
M21 = side.Y,
M31 = side.Z,
M41 = 0,
M12 = up.X,
M22 = up.Y,
M32 = up.Z,
M42 = 0,
M13 = forward.X,
M23 = forward.Y,
M33 = forward.Z,
M43 = 0,
M14 = 0,
M24 = 0,
M34 = 0,
M44 = 1
};
result.Multiply(Matrix4x4.Translation(-position.X, -position.Y, -position.Z));
return result;
}
decompose 方法还为位置变量返回错误的值p
。那么为什么相机工作而实体不工作呢?