I am currently making a game that requires space flight. This script makes the spaceship move in the direction it’s facing, and allows it to turn left and right. Currently, you have to hold down the forward button for it to continue moving forward. I am trying to make it to where when it is moving forward, and you release the forward button, it continues to move forward (That makes it realistic). It is made in JS.
Here is the code:
#pragma strict
var Speed = 5;
var Turn = 50;
function Start () {
}
function Update () {
//transform.Translate(Vector3.forward * 2 * Time.deltaTime);
transform.Translate(Vector3.forward * Input.GetAxis ("Vertical") * Speed * Time.deltaTime);
transform.Rotate(Vector3.up * Turn * Input.GetAxis("Horizontal") * Time.deltaTime); //Turn
}
Depends on how realistic you’re going for. You’re going to want to use the physics system to make it really realistic - the player accelerating would add to its velocity, rather than directly moving it. Add a Rigidbody to your object, then something like this:
(apologies if I leave in any syntax errors, I usually use C#.)
private var rigidbody : Rigidbody;
function Start() {
rigidbody = GetComponent.<Rigidbody>();
}
function FixedUpdate() { //use FixedUpdate instead when dealing with physics
rigidbody.AddForce(transform.forward * Input.GetAxis("Vertical") * Speed); //no Time.deltaTime here
}
Be sure that this is what you want - while it IS realistic, it’s a very different feel and gameplay style from what you had before.
Have the speed in two parts, the maxSpeed and currentSpeed. When the player holds a button down check if the currentSpeed is equal to or greater than maxSpeed. if its not, increment it (acceleration). If the player is no longer holding the button down decrement it (decelerate) it to 0 using Mathf.Clamp(currentSpeed, 0.0f, maxSpeed)