Search Unity

Help! Child rotation, negate offset of parent rotation?

Discussion in 'Scripting' started by Lapsapnow, Jan 2, 2022.

  1. Lapsapnow

    Lapsapnow

    Joined:
    Jul 4, 2019
    Posts:
    51
    Hello.
    I've got a little issue here, that I've been trying to tackle for weeks.

    I have a turret, on a ship, that I need to rotate to face a direction in World Space.
    However, to do so I need to offset the rotation of it's parent.

    How can I do that?

    I attempted to get the offset like this:
    Code (CSharp):
    1. quaternion worldForwards = new quaternion(0, 0, 0, 1f);
    2. quaternion offset = math.mul(worldForwards, parentQuaternionRotation);
    However, it's rotations are not correct when applied to the final quaternion ( see below )

    Here is my code in pure form. float3 is synonymous with Vector3 in Unity.Mathematics

    Code (CSharp):
    1. float3 targetDirection = math.normalize(targeting.relativeTargetPosition);
    2. float3 up = parentLocalToWorld.localToWorld.Up;
    3. quaternion parentRotation = parentLocalToWorld.localToWorld.Rotation;
    4. quaternion thisRotation = localToWorld.Rotation;
    5.  
    6. quaternion final = quaternion.LookRotation(targetDirection, up); // Rotation must respect parent up axis.
    7.  
    8. rotation.Value = final; // final will be offset by parentLocalToWorld.rotation, need to negate.
    9.  
     
    Last edited: Feb 27, 2022
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,491
    Not an answer but so you know, there are dedicated DOTS sub-forums here that might help you better.

    I can always move your post there if you wish.
     
  3. Lapsapnow

    Lapsapnow

    Joined:
    Jul 4, 2019
    Posts:
    51
    Hello Melv, thanks I'd appreciate it if you would.
    Though, this isn't specifically a DOTS issue. It's just Quaternion math. Was hoping someone could teach me.
     
    Last edited: Feb 27, 2022
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,491
    If I follow you correctly, maybe adapting this would help. Get your child world-space rotation and the inverse of the parent world-space rotation and combine or mul them together.

    In short above, the "parentQuaternionRotation" needs to be the inverse (Transform.worldToLocal) or "public static float4x4 inverse(float4x4 m)"

    NOTE: Unity.Mathematics has "public static quaternion inverse(quaternion q)" for this inversion.
     
  5. Lapsapnow

    Lapsapnow

    Joined:
    Jul 4, 2019
    Posts:
    51
    Thank you very much! That's very helpful.
     
    MelvMay likes this.
  6. kellyray

    kellyray

    Joined:
    May 18, 2022
    Posts:
    2
    Hey @Lapsapnow , or anyone for that matter. I am attempting to do something similar and cannot seem to follow. Did you end up figuring this out? And could you elaborate?