Jump for rigidbody


I’m making a 2d side scrolling car game and I want my car to jump but without using a character controller.

Here’s what I have for controls so far:

var speed : float = 10;
var jumpForce : float = 5;

function Update () {
	transform.Translate(Input.GetAxis("Horizontal") * speed * Time.deltaTime,0,0,Space.World);
	transform.localPosition.x = Mathf.Clamp(transform.localPosition.x,-21,21);
		rigidbody.AddForce(Vector3.up * jumpForce);

This will keep the car moving upwards for as long as I hold the jump button, I want the car to reach a max height and then fall back down and not allow another jump until it has hit the ground.

How can I do this?


You will need to check if the car is touching the road or not. For this you can use a raycast in this very same script in the vertically downwards direction and every time the user presses the jump button, you check if the raycast is hitting anything or not, if it is hitting only then you add the force. Make sure that the raycast it not very long nor very short, keep its length at something like 1 meter or something you might have to adjust it for best results.
You need to add only a few lines of code there, if you are not aware of raycast then search for it in the scripting manual, it will provide you with enough info.
Also try using Input.GetButtonDown instead of GetButton, its just a tip anyway, it will also work the other way you have done it.
I Hope this helped!