Divide a number by a Vector3

霸气de小男生 提交于 2020-12-13 04:41:45

问题


Is it possible to divide a number by a Vector3? For example, how can I divide 1 by the scale vector of an object to resize it's child according to it's parent scale without making a new Vector3 applying values of each axis respectivly?


回答1:


There is no such method build-in

but you can simply add an extension method once like

public static class Vector3Extensions
{
    /// <summary>
    /// Inverts a scale vector by dividing 1 by each component
    /// </summary>
    public static Vector3 Invert(this Vector3 vec)
    {
        return new Vector3(1 / vec.x, 1 / vec.y, 1 / vec.z);
    }
}

than later in all your scripts you just have to do e.g.

var parentSize = transform.parent.lossyScale; // e.g. 1, 2, 3

var invertedParentSize = parentSize.Invert();

// -> 1.0, 0.5, 0.333..



回答2:


You can't do it, but if you guarantee all three axis will change scale to the same value like (1, 1, 1) to (0.5, 0.5, 0.5) or at least at the same proportion (100% to 70% in all axis), then you can save into an int the value os one of those axis.

int number = gameObject.transform.localScale.x;

Then, on the child objects you just use the number:

gameObject.transform.localScale *= gameObject.transform.parent.getComponent<someClass>().number;

int variables can only store one value, so you can't use the same variable to allocate data of three axis simultaneously.

the method I gave you is to copy the scale, if you want to keep the size of the childs even if the parent changes it scale then you divide 1/parent scale

int number = 1/gameObject.transform.localScale.x;

gameObject.transform.localScale *= gameObject.transform.parent.getComponent<someClass>().number;



回答3:


You cannot do that as a Vector3 is not a Scalar value.

You can however to mathematical functions using the individual parts of a Vector3(x,y,z).

EX:

var number = 5 * someVector.x; 


来源:https://stackoverflow.com/questions/54809777/divide-a-number-by-a-vector3

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