I’m using this simple script
when I hold the right to the speed increases smoothly
but I do not know, do the speed back to zero smoothly
see my script:
public float acelerate = 5.0f;
public float speedMin = 10.0f;
public float speedMax = 30.0f;
private float moveZ;
public float speed = 0.0F;
private float V;
private float H;
public float timePassed;
void FixedUpdate () {
V = Input.GetAxis("Vertical") *Time.deltaTime;
H = Input.GetAxis("Horizontal")*Time.deltaTime;
Vector3 vt = new Vector3(-V,0, H).normalized;
rigidbody.AddForce( 0, 0, vt.z*speed*8*Time.deltaTime);
if(H>0){
timePassed = Time.time;
speed = Mathf.Lerp(speedMin, speedMax, timePassed/acelerate);
}else{
// my problem....... help me back for zero smoothly?
}
You are mixing and matching things here. Think about a rocket in space. If you keep adding force (since there is no drag), the rocket will go faster and faster. Your code, and specifically your calculation of speed is does not work as any sort of real world calculation. For example using Time.time in the calculation assures that the longer the game runs, the more force you will add per frame. In addition, it seems strange to use horizontal twice…once in calculating vt, and once again to make speed calculations. My suggestion.
- Delete lines 20 - 26 and ‘speed’ altogether.
- Create a forceFactor variable and initialize it to a non-zero value. Start with 5.0;
- In the inspector, select the object this script is attached to and increase the ‘Drag’ setting in the Rigidbody component (it is zero by default).
Your AddForce() will look something like:
rigidbody.AddForce(0,0, H*forceFactor);
Since you are executing this in FixedUpdate(), you don’t need deltaTime or fixedDeltaTime. Your code will all be about balancing your forward force and your drag. The drag will slow your ship down when you back off of ‘Horizontal’. Play with some values until you get the ship to behave like you want.