- Home /
Decrease one number as another gets bigger
Hello this is a very simple question if you're good at math, which i happen not to be! So im getting the distance from an object and there after i calculate a value depending on the distance. But i want it so if the distance is less the higher the calculated value is. How does one achive this?
float dist = Vector3.Distance (transform.position, chars[i].GetComponentInParent<CharController>().transform.position);
//Debug.Log (dist);
if (dist <= 5) {
//Debug.Log (chars [i] + " is close enough");
float calculatedForce = dist * 500; //Calculate here!
Debug.Log (calculatedForce + " " + chars[i].GetComponentInParent<CharController>().name);
chars[i].transform.GetComponentInParent<CharController>().TakeDamage(100, transform.position, calculatedForce);
}
Thanks!
Answer by fluxhackspro · May 08, 2018 at 05:27 PM
As i said it was simple. float calculatedForce = 1 / dist
So if diststance is higher lets say 5, 1 / 5 = 0.2f and if its lower lets say 2, 1 / 2 = 0.5f
Then you can multiply with a value to increase the force Hope i helped someone and sorry for forgetting how to math xD
Remember as distance tends towards zero, this will be exponential, 1/0.0001 = 10000 and if you manage a distance of exactly zero you'll get an exception thrown. To avoid that you could always add 1 to the distance 1/(1+distance).
Alternatively if you want a linear relationship you could do $$anonymous$$athf.$$anonymous$$ax(-distance + X, 0) where X is the maximum distance that would produce a score. That way with X=500 you'd have distance=0 -> 500; distance=500 -> 0;
Your answer