I am looking at this code and do not know what is this magnitude
and normalized
doing and how is this guy using them. In documentation there is only few thing but it doesn't explain much.
Code i am looking at is:
public float minDistance = 1.0f;
public float maxDistance = 4.0f;
public float smooth = 10.0f;
Vector3 dollyDir;
public Vector3 dollyDirAdjusted;
public float distance;
void Awake()
{
dollyDir = transform.localPosition.normalized;
//What has he got with this? Documentation says Returns this vector with
//a magnitude of 1 so if i get it it return's it's length as 1. So what is the point?
distance = transform.localPosition.magnitude;
//Have no idea what he got with this
}
void Update()
{
Vector3 desiredPos = transform.parent.TransformPoint(dollyDir * maxDistance);
//I know what TransfromPoint does but what is he getting with this dollyDir * maxDistance
//Some other code which i understand
}
And while i am here if someone could explain me Mathf.Clamp
Documentation for clamp
is so unclear and how i got it is that i give top and bottom value 1 and 5
and if i set value = 3
it will return 3, but if i set value > 5 it will return 5 and if i set value < 1 it will return 1?
Thanks.
Vector3.magnitude returns a float, its a single dimensional value expressing vector length (so it looses directional information)
Vector3.normalized is a bit of an opposite operation - it returns vector direction, guaranteeing that the magnitude of the resulting vector is one, (it preserves the direction information but looses the magnitude information).
The two are often useful for when you want to seperate those two ways of looking at a vector, for example if you need to have an influcence between two bodies where the influence is inversly proportional to the distance between them, you can do
float mag=(targetpos-mypos).magnitude;
if (mag<maxRange)
{
Vector3 dir=(targetpos-mypos).normalized;
Vector3 newVector=dir*(maxRange-mag);
}
this is the most typical use case for me, I am not sure what the author of the original code meant by his as it does seem he could just use a vector difference without using the two extra calls
Mathf.Clamp returns value of value lies between min and max, returns min if its lower and max if is greater.
Another interesting feature of Vector3 is sqrMagnitude which returns a^2+b^2+c^c without computhing the square root. While it adds a bit to the complexity to the code (you need to compare it with squared distance), it saves a relatively expensive root computation; The slightly optimised but a tiny bit harder to read version would look like this
Vectior3 delta=targetpos-mypos;
if (delta.sqrMagnitude<maxRange*maxRange)
{
Vector3 dir=delta.normalized;
Vector3 newVector=dir*(maxRange-delta.magnitude);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With