# How to stop spaceship when there is no gravity?

Hello! I’m a beginner and have a problem with making my spaceship stop when there is no gravity.
My idea is to make the ship to go forward when the Up key is pressed, and when i release the key, it will stop.
Currently i have made it to go forward when the Up key is pressed, and when the key is released, it goes backward to decrease the speed. But i cant figure out to make it stop…
Here is the code i’ve made so far.

``````using UnityEngine;
using System.Collections;

public class ShipController : MonoBehaviour
{

public float speedForward = 10;
public float forwardBoost = 20;
public float maxSpeed = 20;
public float reverseSpeed = -8;

void FixedUpdate ()
{
//If Up Key is pressed the ship will fly forward
if (Input.GetKey("up"))
{
}

//If the Up key is released the ship will fly backward to decrease
//the speed
else if (rigidbody.velocity.magnitude > 0)
{
}

//If the speed is zero then stop the ship
if (rigidbody.velocity.magnitude == 0)
{
rigidbody.velocity = Vector3.zero;
}

//Set the MAX speed
if (rigidbody.velocity.magnitude > maxSpeed)
{
rigidbody.velocity = rigidbody.velocity.normalized * maxSpeed;
}
}
}
``````

Any ideas on how to do this?

Why not interpolate the velocity towards Vector3.zero when you want to stop? (Vector3.zero is just “new Vector3(0, 0, 0)”)

``````Lerp (firstVec : Vector3, SecondVec : Vector3, t : float)
``````

Here’s an example

``````void FixedUpdate()
{
rigidbody.velocity = Vector3.Lerp(rigidbody.velocity, Vector3.zero, Time.fixedTimeDelta);
}
``````

This will slow a rigidbody to a stop over time. If you want it to go faster or slower to a stop, multiply the fixedTimeDelta (the fixed time since the last update) by a decimal number.

Some terms:

Time.fixedDeltaTime - The interval in seconds at which physics and other fixed frame rate updates (like MonoBehaviour’s FixedUpdate) are performed.

Vector3.Lerp - Interpolates between from and to by the fraction t. This is most commonly used to find a point some fraction of the way along a line between two endpoints (eg, to move an object gradually between those points). This fraction is clamped to the range [0…1]. When t = 0 returns from. When t = 1 returns to. When t = 0.5 returns the point midway between from and to.

(Basically, the closer the “t” value is to 0, the closer to the first vector it will be, but the closer “t” is to 1, the closer it will be to the second vector. So you can either have it interpolate regularly and gradually change a float value from 0 to 1, or you can give it something set like the fixed delta time and it will gradually get closer and closer each time it interpolates.)

If you ever need to know what a function does, google and the Unity docs are amazing.

http://docs.unity3d.com/Documentation/ScriptReference/index.html