问题
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