I am changing a float variable (offRoadRider) at runtime via an input press to a value of 0.1, and when it’s value is equal to 0.1 in turn a boolean (reachedTop) is set to true. The problem is that when pressing the button, my offRoadRider variable isn’t always set to exactly 0.1 and the boolean isn’t always triggered. I would like to add a ± tolerance (boolTolerance) of 0.1, so that when checking the offRoadRider value if it’s between 0.0-0.2 it will still turn on the boolean. I have tried this below but it now doesn’t activate the boolean at all. Any suggestions?
using UnityEngine;
using System.Collections;
public class HydraulicSuspension : MonoBehaviour {
public float offRoadRider = 0.3f;
public bool reachedTop = false;
public float boolTolerance = 0.1f;
public CarDynamics carDynamics;
//Use this before intialization
void Awake(){
carDynamics = GetComponent <CarDynamics>();
}
// Update is called once per frame
void FixedUpdate () {
if((carDynamics.suspensionTravelFront == offRoadRider +- boolTolerance)
&& (carDynamics.suspensionTravelRear == offRoadRider +- boolTolerance)) {
reachedTop = true;
}
else {
reachedTop = false;
}
}
Mathf.Abs(carDynamics.suspensionTravelFront - offRoadRider) <= boolTolerance
or there should be Mathf.Approximately
For clarity and the benefit of others, I would like to add here what I found to be the most effective solution in the end. In the if statement above I first created two checks to see if 1) my variable was less than the maximum + the tolerance value & - the tolerence, and if 2) my variable was more than the minimum - my tolerance & + the tolerance value. By changing the tolerance this allowed me to set exactly how close to the variables I need to be. Here is the part of the script:
if((carDynamics.suspensionTravelFront <= offRoadRider + boolTolerance)
&& (carDynamics.suspensionTravelFront >= offRoadRider - boolTolerance)
&& (carDynamics.suspensionTravelRear <= offRoadRider + boolTolerance)
&& (carDynamics.suspensionTravelRear >= offRoadRider - boolTolerance)) {
reachedTop = true;
reachedBottom = false;
}
else {
reachedTop = false;
}
if((carDynamics.suspensionTravelFront <= lowRider + boolTolerance)
&& (carDynamics.suspensionTravelFront >= lowRider - boolTolerance)
&& (carDynamics.suspensionTravelRear <= lowRider + boolTolerance)
&& (carDynamics.suspensionTravelRear >= lowRider - boolTolerance)) {
reachedTop = false;
reachedBottom = true;
}
else {
reachedBottom = false;
}