- Home /
How can I accelerate my Object to a maximum speed
Currently I'm working on a project , in which you can fly an aircraft. I have got the basic movement of it set up , but it instantly goes to maximum Speed if I press "W". So how can I slowly accelerate it to maximum Speed and decelerate it if I no longer press "W". Thank you very much in advance for your answer.
Here is the script I already made:
using UnityEngine;
using System.Collections;
public class RealisticPlane : MonoBehaviour {
public float maxSpeed = 10;
public float maxLift = 5;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
transform.Rotate ( Input.GetAxis ("Vertical") , Input.GetAxis("RollAxis") , -Input.GetAxis ("Horizontal"));
if (Input.GetKey (KeyCode.W))
{
transform.Translate(Vector3.down * Time.deltaTime * maxSpeed);
}
float heightPosition = Terrain.activeTerrain.SampleHeight (transform.position);
if (heightPosition > transform.position.y)
{
transform.position = new Vector3 (transform.position.x,
heightPosition,
transform.position.z);
}
}
}
Where is your velocity for the plane? Normally, if you press W you'd increase the velocity, until you reach maxSpeed
. If W is not pressed, then you'd reduce the velocity, presumably down to zero. In your code you just apply maxSpeed
.
I tried to get the velocity , but since the Plane doesn't have a rigidbody I can't use rigidbody.velocity.
So create a variable called velocity and use that.
Answer by EmmaEwert · Dec 27, 2014 at 08:42 PM
Considering your class is called RealisticPlane
, you may intend to add physical simulation of forces, momentum etc. Assuming this is the case;
Attach a rigidbody, and apply forces through Rigidbody#AddForce or Rigidbody#AddRelativeForce. This way, you can add a forward force every physics frame (in FixedUpdate, not Update) that the W-key is held.