Skip to content

Instantly share code, notes, and snippets.

@drZool
Created April 18, 2018 11:31
Show Gist options
  • Select an option

  • Save drZool/befb102d37a81b332862b0583e839d54 to your computer and use it in GitHub Desktop.

Select an option

Save drZool/befb102d37a81b332862b0583e839d54 to your computer and use it in GitHub Desktop.
Keep position/rotation of child object same as a world object by moving/rotating it's parent.
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class MatchPositionWithChild : MonoBehaviour
{
public Transform target;
public Transform follower;
public Transform anchor;
public bool UpdatePositions;
public bool AlwaysUpdate;
static public Quaternion GetLocalRotation (Transform parent, Transform child)
{
Quaternion result = child.localRotation;
while (child.transform.parent != parent && child != null) {
result = child.transform.parent.localRotation * result;
child = child.transform.parent;
}
return result;
}
void Update ()
{
if (!UpdatePositions && !AlwaysUpdate)
return;
if (target == null)
return;
if (follower == null)
return;
if (anchor == null)
return;
UpdatePositions = false;
var relRotation = target.rotation * Quaternion.Inverse (GetLocalRotation (follower, anchor));
var relPosition = follower.InverseTransformPoint (anchor.position);
follower.rotation = relRotation;
Vector3 delta = target.position - anchor.position;
follower.SetPositionAndRotation (follower.position + delta, relRotation);
}
public static void RotateAndMoveParentRelativeToChild (Transform parentToMove, Transform childAnchor, Transform targetPositionAndRotation)
{
var relRotation = targetPositionAndRotation.rotation * Quaternion.Inverse (GetLocalRotation (parentToMove, childAnchor));
var relPosition = parentToMove.InverseTransformPoint (childAnchor.position);
parentToMove.rotation = relRotation;
Vector3 delta = targetPositionAndRotation.position - childAnchor.position;
parentToMove.SetPositionAndRotation (parentToMove.position + delta, relRotation);
}
// for (int i = 0; i < 1; ++i) {
// var relRotation = target.rotation * Quaternion.Inverse (anchor.localRotation);
// //var rotation = (relRotation * objectToMatch.rotation);
//
// // var worldRelOffset = rotation * relPosition;
// var relPosition = follower.InverseTransformPoint (anchor.position);
// //var position = objectToMatch.position - worldRelOffset;
// follower.rotation = relRotation;
// Vector3 delta = target.position - anchor.position;
// follower.SetPositionAndRotation (follower.position + delta, relRotation);
// //parentToMove.SetPositionAndRotation (objectToMatch.position, rotation);
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment