- Home /
Float speed doesn't listen a condition
public float speedDef = 0.25f; //Setted speed
public float speedMax = 1.0f;
private float speedMin = 0.0f;
public float speedRes = 0.001f; //To restore speed to initial speed (speedBase)
public float accel = 0.005f;
public float decel = 0.0005f;
public float brake = 0.0025f;
private float speedCur; //Current speed in calculation
private float speedBase; //Initial speed to memorize
private Vector3 lastPosition = Vector3.zero;
void Start()
{
speedBase = speedDef;
}
void FixedUpdate()
{
//Speed Calculation
speedCur = (transform.position - lastPosition).magnitude;
lastPosition = transform.position;
Debug.Log(speedCur);
//Default Speed
transform.position += transform.forward * speedDef;
//SPACE (Acceleration)
if (Input.GetKey(KeyCode.Space))
{
//Acceleration
if (speedCur < speedMax)
{
speedDef += accel;
}
}
else
{
//Deceleration
if (speedCur > speedBase)
{
speedDef -= decel;
}
}
//LEFT SHIFT (Brake)
if (Input.GetKey(KeyCode.LeftShift))
{
if (speedCur > speedMin)
{
speedDef -= brake;
}
else
{
speedDef = speedMin;
}
}
else
{
if (speedDef < speedBase)
{
speedDef += speedRes;
}
}
}
Everything above that is fine except in brake function, when I pressed Left Shift for first time, the player brakes until that he has speed 0. It worked but if after that, I release this button to let the player to restore his speed then I press again the Left Shift, the speed goes over -0,x until -1, -2, -3,... even with very clear condition like this:
else
{
speedDef = speedMin;
}
It doesn't want to listen it... How to solve it?
Thanks!
Answer by NPnpNPnpNP · Jan 27, 2021 at 08:12 PM
You can use speedDef = Mathf.Clamp(speedDef , speedMin, speedMax);
at the end of the Update() function to be sure that speedDef
will always be higher or equal to speedMin
and lower equal to speedMax
.
Wonderful, it worked very well. I didn't think about that. Thanks a lot! :)
I found that we can solve also it by removing the unnecessary part : else { speedDef = speed$$anonymous$$in; }
and adding one more condition like that :
if (Input.GetKey(KeyCode.LeftShift))
{
if (speedCur > speed$$anonymous$$in && speedDef > speed$$anonymous$$in)
{
speedDef -= brake;
}
}
else
{
if (speedDef < speedBase)
{
speedDef += speedRes;
}
}
But the solution from NPnpNPnpNP is more accurate in calculation of float. FYI at everyone
Your answer
Follow this Question
Related Questions
Checking an increasing number 1 Answer
[mecanim] conditions for float are < or > but no == 1 Answer
Can't equalize float angle 1 Answer
value range of Sprite sortingOrder 0 Answers