[Newbie] How to make character jump only once?

Updated on February 23, 2019 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on February 21, 2019

Hi, I’m newbie and just start to learn coding & how to make a game in Unity. I’ve just finished from watching this tutorial : https://www.youtube.com/watch?v=j48LtUkZRjU&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6

and I’m so happy that I’ve just created my first game. And now I’m trying to modify it a little bit, like when i press W, it’s move forward or when i type S, it’s move backward and yep, it’s working. However, I’ve some problem with jumping right now. When i press Space, sure it does jump. But only once until I finish my game. I want to make it can jump again after player’s grounded. Please check my code :

using UnityEngine;
public class PlayerMovement : MonoBehaviour {
    public Rigidbody rb;
    public float forwardForce = 2000f;
    public float sidewalksForce = 500f;
    public float backwardsForce = -2000f;
    public float jumpForce = 500f;
    public bool jumpLoop;
    void OnCollisionEnter(Collision colliderInfo)
    {
        if (rb.gameObject.tag == "Ground" && jumpLoop == true)
        {
            jumpLoop = false;
        }
    }
    void OnCollisionExit (Collision colliderInfo)
    {
            jumpLoop = true;
    }
    void Update() {
        if (Input.GetKey("w"))
        {
            rb.AddForce(0, 0, forwardForce * Time.deltaTime);
        }
        if (Input.GetKey("s"))
        {
            rb.AddForce(0, 0, backwardsForce * Time.deltaTime);
        }
        if (Input.GetKey("space") && jumpLoop==false)
        {
            rb.AddForce(0, jumpForce , 0 * Time.deltaTime);  
        }
        if (Input.GetKey("d"))
        {
            rb.AddForce(sidewalksForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewalksForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
        if(rb.position.y < -1f)
        {
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

What should i do to fix my code?

  • Liked by
Reply
1 on February 21, 2019

You’re not checking for the ground in your collision. You’re checking if rb is tagged as ground, but rb is us, the player.

Just swap out rb for colliderInfo.collider

and of course, make sure your ground is tagged as “Ground”

on February 23, 2019

Thank you so much!

 

Show more replies
  • Liked by
Reply
Cancel