21 July 2020

Math - Calculate a look-at matrix for OpenGL (II)

This is a simplification of the method to create a look-at or camera matrix from 2017. Based on DirectX documentation, it creates the matrix in one step, without multiplication. The matrix is created transposed for OpenGL. This method takes in a Vector3 Position and Direction.

This matrix doesn't work when looking straight up or down, because in that case the x-axis cross product fails. To solve this, manually set the x-axis in that case.

bool isVertical = direction.X == 0 && direction.Z == 0;
var up = new Vector3(0, 1, 0);
var zAxis = direction.Normalized();
var xAxis = isVertical ? new Vector3(1, 0, 0) : Vector3.CrossProduct(up, zAxis).Normalized();
var yAxis = Vector3.CrossProduct(zAxis, xAxis);

return new Matrix(
    xAxis.X, xAxis.Y, xAxis.Z, -Vector3.DotProduct(xAxis, position),
    yAxis.X, yAxis.Y, yAxis.Z, -Vector3.DotProduct(yAxis, position),
    zAxis.X, zAxis.Y, zAxis.Z, -Vector3.DotProduct(zAxis, position),
    0, 0, 0, 1
);

No comments:

Post a Comment