# Make my Cube jump?

Hey guys I just finished the 3D tutorial so my knowledge is pretty basic, before starting the next tutorial I wanted to try some things out. I did the 3D tutorial and wanted to add a script for jumping, after googleing I used this script:

``````public float speed;
public float jumpSpeed;
public Text countText;
public Text winText;

private Rigidbody rb;
private int count;

void Start ()
{
rb = GetComponent<Rigidbody> ();
count = 0;
SetCountText ();
winText.text = "";
}

void FixedUpdate()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

if(Input.GetKey (KeyCode.Space)){
}
``````

It kinda works, but not like I want it to work, while pressing space it goes in the air, but if I hold space it starts to fly, what do I need to add so it will go up for 1-2 seconds and then fall?
I’m pretty new to unity so an explanation would be great!

Hi

tXxy

You could use a boolean variable to check if your object is in the air or already on your ground(plane). This is my version of your code:

public float speed;
public float jumpSpeed;

``````private Rigidbody rb;
private int count;

//Adding the boolean variable onPlane to check if object touching the ground
private bool onPlane;

void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
//make onPlane true
onPlane = true;

}

void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");

Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

//If onPlane true you can hit Space and jump, otherwise not possbile
if (onPlane)
{
if (Input.GetKey(KeyCode.Space))
{

rb.velocity = new Vector3(0f, jumpSpeed, 0f); // I like more velocity than AddForce
//After you hit jump, make onPlane false, so hitting Space for the second time or
// holding it wouldn't change anything
onPlane = false;
}
}

}
//after the object touches the floor again, make onPlane true
private void OnCollisionEnter(Collision collision)
{
//Notice you have to create a tag for this method. You can name it the way you want.
if (collision.gameObject.CompareTag("Plane"))
{
onPlane = true;
}
}
``````