Hello,
i’d like to know the source code of LookAt function. I try make it in c++, but its work wrong.
Hello,
i’d like to know the source code of LookAt function. I try make it in c++, but its work wrong.
It’s not public. However, you can take a look at the CreateLookAt function of the .NET Framework, which implements a similar functionality: Matrix4x4 .NET Reference source (line 1050).
Yes thank you. I found a similar function, even implemented it. Only I do not fully understand how to apply the result of this function. I tried this: translated rotation.eulerAngles into Vector4 homogeneousRotation = new Vector4(eulerAngles.x, eulerAngles.y, eulerAngles.z, 1); multiplied the resulting Matrix4x4 by Vector4 and from this I set the eulerAngles of the object. But this does not give the desired result.
private void HandleObj(Transform obj, Vector3 target)
{
if (obj != null)
{
// wrist.LookAt(target);
// return;
Matrix4x4 rotationMatrix = LookAt2(transform.position, target, Vector3.up);
var eulerAngles = obj.rotation.eulerAngles;
Vector4 homogeneousRotation = new Vector4(eulerAngles.x, eulerAngles.y, eulerAngles.z, 1);
var newAngel = MultiplyMatrixWithVector4(rotationMatrix, homogeneousRotation);
obj.transform.eulerAngles = new Vector3(newAngel.x, newAngel.y, newAngel.z);
}
}
public static Matrix4x4 LookAt2(Vector3 eye, Vector3 target, Vector3 up)
{
Vector3 zaxis = Vector3.Normalize(eye - target);
Vector3 xaxis = Vector3.Normalize(Vector3.Cross(up, zaxis));
Vector3 yaxis = Vector3.Cross(zaxis, xaxis);
Matrix4x4 result = Matrix4x4.zero;
result.m00 = xaxis.x;
result.m01 = yaxis.x;
result.m02 = zaxis.x;
result.m03 = 0.0f;
result.m10 = xaxis.y;
result.m11 = yaxis.y;
result.m12 = zaxis.y;
result.m13 = 0.0f;
result.m20 = xaxis.z;
result.m21 = yaxis.z;
result.m22 = zaxis.z;
result.m23 = 0.0f;
result.m30 = -Vector3.Dot(xaxis, eye);
result.m31 = -Vector3.Dot(yaxis, eye);
result.m32 = -Vector3.Dot(zaxis, eye);
result.m33 = 1.0f;
return result;
}
public static Vector4 MultiplyMatrixWithVector4(Matrix4x4 matrix, Vector4 vector)
{
//matrix row * vector column
var i0 = (matrix[0, 0] * vector.x + matrix[0, 1] * vector.y + matrix[0, 2] * vector.z +
matrix[0, 3] * vector.w);
var i1 = (matrix[1, 0] * vector.x + matrix[1, 1] * vector.y + matrix[1, 2] * vector.z +
matrix[1, 3] * vector.w);
var i2 = (matrix[2, 0] * vector.x + matrix[2, 1] * vector.y + matrix[2, 2] * vector.z +
matrix[2, 3] * vector.w);
var i3 = (matrix[3, 0] * vector.x + matrix[3, 1] * vector.y + matrix[3, 2] * vector.z +
matrix[3, 3] * vector.w);
return new Vector4(i0, i1, i2, i3);
}
Tell me, please, how to properly apply the resulting Matrix4x4?
@BastianUrbach