Unity Lossy Scaling implementation

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 12:25:13

问题


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 to a paralelogram. Gooing I found transform.lossyScale that should fix my problem but I don´t know how to implement it.

TL:DR how to implement transform.lossyscale to prevent parent-child scaling issues.

current code

float currentR = transform.eulerAngles.x;

    if(currentR < 30){
        transform.Rotate (rotation * Time.deltaTime * 3);
}

回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/47417317/unity-lossy-scaling-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!