LookAt with Unity.Mathematics

I have a cube that rotated Z for 45 degrees and shift by X for -5f.

I want to rotate it orbit like with lookAt around center of coordinates (float3(0f, 0f, 0f)).
I try this:

xRot = speedH * Input.GetAxis("Mouse X");
yRot = speedV * Input.GetAxis("Mouse Y");

inputDeps = Entities.WithAll<BoxComponent>().ForEach((ref Rotation rotation, ref Translation position, ref MoveComponent mov) =>
  {
      var rot = rotation.Value;
      float3 pos = position.Value;
      var v = Quaternion.AngleAxis(xRot, Vector3.up) * Quaternion.AngleAxis(yRot, Vector3.right) * pos;

      position.Value =  v; // position works

      // orientation does not work
      float3 forward = math.mul(rot, math.normalize(position.Value));
      float3 up = new float3(0f, 1f, 0f);
      up = math.mul(rot, up) - (forward * math.dot(up, forward));
      rotation.Value = quaternion.LookRotation(forward, math.normalize(up));
})
.Schedule(inputDeps);

If I use position.Value for forward vector it’s ok but I need to rotate forward vector for relative rotation.
I tried to save initialRotation quaterion and use forward = math.mul(mov.initRot, math.normalize(position.Value)); or use float(0f,0f,1f) as vector to rotate but all my tries cause wrong rotation.

Maybe I understand quaterions wrong…

Might be it will be usefull for some one:

my solution looks like:

float3 pos = position.Value;
quaternion rot = rotation.Value;
float3x3 rot3x3 = new float3x3(rot);

quaternion newRot = quaternion.EulerXYZ(math.radians(yRot), math.radians(xRot), 0);
position.Value =  math.rotate(newRot, pos);
                     
// c0 - right, c1 - up, c2 - forward
float3 up = rot3x3.c1; 
float3 forward = rot3x3.c2;

var initialRot = quaternion.LookRotationSafe(forward, up); 
rotation.Value = math.mul(math.mul(initialRot, math.mul(math.inverse(initialRot), newRot)), initialRot);
6 Likes