Home > Enterprise >  Maintain two gameobject distance and ankle
Maintain two gameobject distance and ankle

Time:03-28

I have two gameobject , and I need the first one moving another position then the second one is maintaining the preview distance and ankle, is unity have a way to do that?

enter image description here

enter image description here

CodePudding user response:

Simplest would of course be: Parenting.

  • make you second object a child of the first one
  • Move the first one like you wish
  • The child is automatically transformed along with it
  • (optional) Finally un-parent again

something like e.g.

// the one you will move
Transform white;
// the one which you want to keep the same delta transforms for
Transform red;

// store original parent for parenting it back when done
var oldParent = red.parent;
// also store original sibling index if order is important
var siblingIndex = red.GetSiblingIndex();
// nest the red under the white
red.SetParent(white);

// transform white
white.position = XY;
white.rotation = ABC;

// restore original hierarchy
red.SetParent(oldParent);
red.SetSiblingIndex(siblingIndex);

In situations where parenting is not an option you can

  • Store the position and rotation offset
  • Update your first object
  • Assign the position and rotation offset back

something like e.g.

// the one you will move
Transform white;
// the one which you want to keep the same delta transforms for
Transform red;

// Store position and rotation delta in the local space of white
var localPositionDelta = white.InverseTransformPoint(red.position);
var localRotationDelta = Quaternion.Inverse(white.rotation) * red.rotation;

// transform white
white.position = XY;
white.rotation = ABC;

// assign back the local space delta to red
red.position = white.TransformPoint(localPositionDelta);
red.rotation = localRotationDelta * white.rotation;
  • Related