1
\$\begingroup\$

I am back once again. This time with a basic 2D platformer game. I would like to allow my player to jump but only if the ground bool checks as true. I would like to fix my script so that upon collision with the ground the player is able to jump, but while the player is in the air the player is not able to jump. My platform has a box collider and my player has a collider as well as a rigidbody. How do I go about fixing my script to allow this system to go into effect? Please and Thank you!

public class MovePlayer : MonoBehaviour {

    public float speed = 0f;
    public float height = 0f;
    public GameObject player;


    private bool grounded = false;

    void OnCollisionEnter2D(Collision2D coll) 
    {
        if (coll.gameObject.tag == "ground")
            grounded = true;
            return;
    }
    // Use this for initialization
    void Movement () 
    {
        if (Input.GetKey (KeyCode.RightArrow)) 
        {
            transform.Translate(Vector3.right * speed * Time.deltaTime);
        }

        if (Input.GetKey (KeyCode.LeftArrow))
        {
            transform.Translate (Vector3.left * speed * Time.deltaTime);
        }


        while (grounded = true) 
        {
             Jump();
        }
    }

    void Jump()
    {
        if (Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKey (KeyCode.Space)) {
            transform.Translate (Vector3.up * height * Time.deltaTime);
            return; 
        }
    }

    // Update is called once per frame
    void Update () 
    {

        Movement ();
    }
}
\$\endgroup\$
2
\$\begingroup\$

You have an error:

while (grounded = true) 
{
  Jump();
}

So each time Movement() is called - each frame - grounded will be true. Use "grounded == true" as condition check. But don't forget to set grounded var back to false or you'll see infinite loop.

I suggest you to change workflow and use State design pattern or something like that to not mess with different bools and flags.

\$\endgroup\$
0
\$\begingroup\$

I think what you want is void OnCollisionStay(); It is a built in (intrinsic) function used by Unity. When the unit enters or stays in any collision you check to make sure the collidable object is tagged as a floor then if the player is hitting the "Jump" button, jump. Its not elegant but it works just fin in my experience.http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionStay.html This is the 3D version. There is a 2D version as well if you wanted that.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.