Created
April 26, 2018 17:24
-
-
Save julenka/c59f682684dce14a52e62001c6b6ff62 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| /// <summary> | |
| /// Ensures that the position of this object relative to ObjectToFollow | |
| /// remains the same, in the frame of reference of their first common ancestor | |
| /// </summary> | |
| public class MatchPosition : MonoBehaviour | |
| { | |
| public Transform ObjectToFollow; | |
| private Vector3 commonAncestorOffset; | |
| private Transform commonAncestor; | |
| // Use this for initialization | |
| void Start() | |
| { | |
| commonAncestor = FindCommonAncestor(transform, ObjectToFollow); | |
| // We want the offset me -> follow IN COMMON ANCESTOR SPACE | |
| commonAncestorOffset = commonAncestor.InverseTransformDirection(transform.position - ObjectToFollow.position); | |
| Debug.Log(string.Format("Common ancestor is {0} offset is {1}", commonAncestor.name, commonAncestorOffset)); | |
| } | |
| /// <summary> | |
| /// Returns the common ancestor between A and B, or null if no common ancestor is found | |
| /// </summary> | |
| /// <param name="a"></param> | |
| /// <param name="b"></param> | |
| /// <returns></returns> | |
| private Transform FindCommonAncestor(Transform a, Transform b) | |
| { | |
| List<Transform> aAncestors = new List<Transform>(); | |
| Transform aCurrent = a; | |
| while(aCurrent != null && aCurrent != a.root) | |
| { | |
| aAncestors.Add(aCurrent); | |
| aCurrent = aCurrent.parent; | |
| } | |
| Transform bCurrent = b; | |
| while(bCurrent != null && bCurrent != b.root) | |
| { | |
| if (aAncestors.Contains(bCurrent)) | |
| { | |
| return bCurrent; | |
| } | |
| bCurrent = bCurrent.parent; | |
| } | |
| return null; | |
| } | |
| // Update is called once per frame | |
| void Update() | |
| { | |
| transform.position = ObjectToFollow.position + commonAncestor.transform.TransformDirection(commonAncestorOffset); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment