- Home /
Beginner Question
I just recently started using Unity and am making a simple script that has a cube jump when you hit space. I tried to make it so you could only jump once until you were grounded again but for some reason you can jump twice (No more than twice) instead of once. Since the object starts at y = 0.5 I tried to make it so while it was above that you couldn't jump. I know there are much easier ways to do this and I would like to know them but I was trying to figure it out myself.
Here is the code:
using UnityEngine;
using System.Collections;
public class JumpingCube : MonoBehaviour {
public int jumpForce = 10;
private bool grounded = true;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (grounded)
if (Input.GetButtonDown ("Jump")) {
grounded = false;
GetComponent<Rigidbody> ().AddForce (0, jumpForce, 0);
}
if (transform.position.y <= .5)
grounded = true;
}
}
A little suggestion: Change your script from
if (grounded){
if (Input.GetButtonDown ("Jump")) {
grounded = false;
GetComponent<Rigidbody> ().AddForce (0, jumpForce, 0);
}
}
to
if (grounded && Input.GetButtonDown ("Jump")){
grounded = false;
GetComponent<Rigidbody> ().AddForce (0, jumpForce, 0);
}
(put both of the "if" statements' conditions in the same "if" statement)
it's a bit neater and easier to read. At least for me.
Answer by TheShadyColombian · Apr 30, 2015 at 08:53 PM
I suggest using a Trigger collider under your GameObject and checking if it has been triggered to enable the "grounded" bool, as if it lands and it is higher than 0.5 in the y axis it wouldn't jump.
Obviously, ignore this if that is irrelevant for your game :)
I agree with this - or, at least, a Raycast would also do the trick. This would help if your character controller was doing more platfor$$anonymous$$g than just the single plane at .5
True! Though (I find) this involves a lot more program$$anonymous$$g, so she/he might prefer the collider, but raycas is a lot better, specially for fast collisions (bullets etc.)
Answer by VRKeith · May 01, 2015 at 03:32 PM
Unity has a function for performing Rigidbody physics in an update loop. Try changing the function from
void Update()
to
void FixedUpdate()
Also, make that an else if for the second condition.
While FixedUpdate() is the proper place for physics processing, it's not an adequate location for input recognition. For the best interaction between input and physics, you would want to carefully utilize a mixture of input in Update() and use of flags set by that input in FixedUpdate().
Your answer
Follow this Question
Related Questions
Issues with jump control for player 1 Answer
Add arrays to a big array? 2 Answers
Is there a way I could combine these scripts? If so, how? 1 Answer