Search Unity

Position and rotate object relative to two other objects

Discussion in 'Scripting' started by AshyB, Apr 11, 2021.

  1. AshyB

    AshyB

    Joined:
    Aug 9, 2012
    Posts:
    191
    Hi folks,

    I've got a character with a rig and some IK, I'm trying to position the hand based on the position and rotation of a target object, but offset by another object that is a child of the hand.

    For example, the hand bone's pivot is at the wrist, I can make the wrist follow the IK target easily enough but then the middle of the hand is not in the correct position. So I have another object that is a child of the hand and is positioned locally in the middle of the hand. I want to use the offset of this child to determine where the wrist should be positioned. If that makes sense.

    After a metric-ton of Googling, I feel I'm close and heading in the right direction but I just can't get it.

    My train of thought is, the hand bone (wrist pivot) needs to be at the same position of the target object, but offset by the middle of the palm object. So I'm thinking;

    Code (CSharp):
    1.  
    2. hand.position = target.rotation * target.TransformDirection(middlePalm.localPosition) + target.position;
    3.  
    This works when you move the target object around, great. But when you rotate the target object the middle of the palm basically "orbits" around the target object. Not good.

    So I'm thinking I need to rotate the hand but based on the target rotation offset by the middle of the palm position (so the middle palm object is basically the pivot point for rotations). Something like;

    Code (CSharp):
    1.  
    2. hand.rotation = target.rotation * Quaternion.Euler(target.TransformDirection(middlePalm.localPosition) + target.position);
    3.  
    But that doesn't work either. I think I should be using transformPoint also as I'm trying to offset the rotation and position by a point and not a direction, but it seems to work better with transformDirection.

    At the moment I'm basically just trying a whole bunch of different combinations to try and it working, any advice would be appreciated.

    Thanks.