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!