Hi,how do I compare 2 vectors?
Ex: if vectorone is almost the same as vectortwo by a percentage then do something;
I want to be able to do something if the vectors are almost the same , the error being another variable.
You can use Vector3.Distance(firstVector, secondVector). It returns a float value that gives you the distance between two coordinates in Unity3d-Units.
It depends on how you want it to be, according to your problem, this might help -
//UnityScript
var vctr1 : Vector3; // first vector
var vctr2 : Vector3; // second vector
var factor : float; // Distance you want between 2 vectors.
var dis : float; // distance between 2 vectors
function Calc()
{
dis = Vector3.Distance(vctr1, vctr2); // Calculating Distance
if(dis <= factor) // checking if distance is less than required distance.
{
//do something
}
}
However, if you want to calculate/check on only a single axis, like if you want to know if player has crossed destination in Z-axis, i.e., if player is ahead of destination,
then this will be more effective -
if(player.position.z > destination.position.z)
{
//do something
}
The above process can be used for any axis.
Finally, it depends on how you want it, and how you use it.
You can use Distance as @Sarthak123 showed, that would be the simplest, but won’t give more control over what you wanna do. Writing you own function should be quite simple. You could do something like
//With absolute value
public bool Approximately(Vector3 me, Vector3 other, float allowedDifference)
{
var dx = me.x - other.x;
if (Mathf.Abs(dx) > allowedDifference)
return false;
var dy = me.y - other.y;
if (Mathf.Abs(dy) > allowedDifference)
return false;
var dz = me.z - other.z;
return Mathf.Abs(dz) >= allowedDifference;
}
//With percentage i.e. between 0 and 1
public bool Approximately(Vector3 me, Vector3 other, float percentage)
{
var dx = me.x - other.x;
if (Mathf.Abs(dx) > me.x * percentage)
return false;
var dy = me.y - other.y;
if (Mathf.Abs(dy) > me.y * percentage)
return false;
var dz = me.z - other.z;
return Mathf.Abs(dz) >= me.z * percentage;
}
You can also write a function that take in a vector to compare in a similar fashion, so you’ll be able to send different values for each element.