Unity Lossy Scaling implementation

后端 未结 1 1849
面向向阳花
面向向阳花 2021-01-28 05:19

I am currently working with Unity and transform.rotation. The problem is that I have 2 rotating objects as parent-child. This makes the child scale weirdly and going from a box

相关标签:
1条回答
  • 2021-01-28 06:05

    Ideally, if you don't want the child to inheirt the scale of the parent, don't make it a child of said parent :P However. If you must, you can make a child that reverses the scale of the parent (So it would have the opposite scale of the parent)

    Than make your new child a child of that child :)

    You can use this general purpose script, put this on the child at it shouldn't have any issues being rotated at runtime even if it has a scaled parent :) (It will do the thing I described above using code)

    public class IgnoreParentScale : MonoBehaviour {
    
    Transform scaleInversionParent;
    
    void Awake () {
        scaleInversionParent = new GameObject ("ScaleInversionParent").transform;
        scaleInversionParent.SetParent (transform.parent);
        scaleInversionParent.localPosition = Vector3.zero;
        scaleInversionParent.eulerAngles = Vector3.zero;//Zero out anything but the scale
        UpdateScaleInversion ();
        transform.SetParent (scaleInversionParent, true);
    }
    void LateUpdate () {
        UpdateScaleInversion (); //Only if you are changing the scale at run time.
    }
    void UpdateScaleInversion () {
        Vector3 invertedScale = scaleInversionParent.parent.localScale;
        invertedScale = new Vector3 (1f / invertedScale.x, 1f / invertedScale.y, 1f / invertedScale.z);
        scaleInversionParent.localScale = invertedScale;//This scale will invert the parents scale
    }
    }
    

    Alternatively:

    You can use this script to create a new parent that inherits the position and rotation of the original parent, but ignores it's scale.

        public class IgnoreParentScale : MonoBehaviour {
    
        Transform originalParent;
        Transform newParent;
    
        void Awake () {
            newParent = new GameObject ("").transform;
            originalParent = transform.parent;
    
            UpdateNewParent ();
            transform.SetParent (newParent);
        }
        public void LateUpdate () {
            UpdateNewParent ();
        }
        void UpdateNewParent () {
            newParent.transform.position = originalParent.transform.position;
            newParent.transform.rotation = originalParent.transform.rotation;
        }
    }
    
    0 讨论(0)
提交回复
热议问题