# Variable not decreasing during runtime (C#)

Greetings,

I am experimenting with controls for a space ship and after completing the most basic of controls I decided to put limits on the ship’s speed and hit a problem I can’t seem to find a solution to.

When moving forward I have a variable A that is compared to a variable B and as long as A is less than B then A will increase and the speed of the ship will increase.

The problem I’m experiencing is that when I move in the opposite direction (backwards) I use the same variable A and instead of the number decreasing it would just place a “-” in front of it.

So, if the object moves forward it will gain a speed of +5.5, when it moves backwards instead of slowly decreasing the number it will get a value of -5.5 which will increase normally. The same thing happens in reverse from this point on.

Below is the code:

``````if(Input.GetButton("W") && currentSpeed < topSpeed){
currentSpeed = Time.time + move;
_cachedRigidbody.AddForce(Vector3.forward * currentSpeed * move * _cachedRigidbody.mass);
}
if(Input.GetButton("S")){
currentSpeed = -Time.time + move;
_cachedRigidbody.AddForce(Vector3.back * -currentSpeed * move * _cachedRigidbody.mass);
}
``````

Any help would be appreciated.

Thank you.

Since you are not setting the velocity but instead are using AddForce, ‘currentSpeed’ is not the current speed. It is the amount of force being applied. Based on your code above and you saying you want to limit ‘Z’, I’m assuming movement towards positive ‘Z’ on the world axes is ‘backward’. If I can assuming there are no collisions and the direction of your ships movement will always be aligned with the world axes, you can do this:

``````var v3 = _cachedRigidbody.velocity;
if (v3.z > topSpeed)
v3.z = topSpeed;
_cachedRigidbody.velocity = v3;
``````