- Home /
Jump for rigidbody
Hi,
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);
if(Input.GetButton("Jump")){
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?
Thanks, Stuart
Answer by adrenak · Feb 20, 2012 at 07:00 PM
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!
Thanks but then as soon as the raycast loses contact with the ground then the force will stop being applied?
Your answer
Follow this Question
Related Questions
Why is it so hard to make a rigidbody jump in the unity engine? 1 Answer
My jumping script has errors 1 Answer
Inconsistent Jump height 3d 3 Answers
Change rigidbody's jumping speed 2 Answers
Jumping increases movement speed 1 Answer