Home > Mobile >  "void OnCollisionStay()" not functioning properly?
"void OnCollisionStay()" not functioning properly?

Time:12-05

I'm having issues with ground detection in my jump code for my 3d game. I'm certain the other parts of the jump script work, but I'm new to coding in C# so of course I might be wrong.

[RequireComponent(typeof(Rigidbody))]
public class Movement : MonoBehaviour{
    public CharacterController controller;
    public float speed = 12f;

    //inputs 
    float x, z;
    public bool isGrounded;

    //jump
    public Vector3 jump;
    public float jumpForce = 400;

    Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0.0f, 2.0f, 0.0f);

    }

    void OnCollisionStay()
    {
        isGrounded = true;
    }

    
    // Update is called once per frame
    void Update()
    {
        //walking n stuff
        x = Input.GetAxis("Horizontal");
        z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x   transform.forward * z;

        transform.position  = move * Time.deltaTime * speed;

        controller.Move(move * speed * Time.deltaTime);

        //jumping
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
            rb.AddForce(jump * jumpForce, ForceMode.Impulse);
        isGrounded = false;

It always shows that I'm not grounded in unity, so therefore nothing happens when I press space, I don't get any errors or anything. I think it might be the void OnCollisionStay() part that is the issue, thankyou in advance to anyone who can help.

CodePudding user response:

The method OnCollisionStay() will not be triggered if there is already collision before the scene loads. You need to set the default value for isGrounded to true by default or set it anywhere in the initialization time (Awake/Start).

Either ways there is something missing in your code, your Jump if statements missing curly-brackets.

        //jumping
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded) 
            rb.AddForce(jump * jumpForce, ForceMode.Impulse); // this is executed if the statement is true
        isGrounded = false; // THIS IS ALWAYS EXECUTED

Fixed code:

  //jumping
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        rb.AddForce(jump * jumpForce, ForceMode.Impulse);
        isGrounded = false;
    }

Good reference to check regarding order of execution.

Guide regarding OnTriggerStay

  • Related