[Solved] Have I overlooked something in my "Fall Damage" script? It doesn't seem to work properly.

So I am using a CharacterController and trying to detect falling via the code below.

I think there’s an issue with resetting the “airTime” variable at the end because if I don’t reset it and just jump up and down it eventually works fine. :confused:

“airTime” also increments OK if I print it to console but even if it’s over “maxFallTime” (“1.2345” for example) it doesn’t seem to catch it.

Anyway, here’s the relevant part of the code:

     public float maxFallTime = 1f;

     private float airTime = 0f; 

     public PlayerController player;


     void Update () {

             FallingPlayer();

     }

    

       private void FallingPlayer(){

  
             if (!player.controller.isGrounded)

             {

                 airTime += Time.deltaTime;

                 //Debug.Log("Airtime = " + airTime);

             }


             if (player.controller.isGrounded && airTime > maxFallTime)

             {

                 Debug.Log("PLAYER HURT!");

                 airTime = 0f;

             }

             if (player.controller.isGrounded && airTime <= maxFallTime)

             {

                 //Debug.Log("AIRTIME RESET!");

                 airTime = 0f;

             }


         }

surely if the player is grounded the airTime should be set to 0 regardless of what it contains. Currently if Airtime is over maxFallTime and player is grounded, it will trigger player is hurt, reset it to zero, then enter the next if statement you have declared, if grounded and airtime is less or equal than maxFallTime, resetting it again.

This probably doesn’t matter too much as all you do is set it to zero again, but it will probably cause bugs in the future as I can’t imagine this is desired behaviour, a simple solutino is make it an else if statement, but i would go further into refactoring it to soemthing like,

if not grounded
     incremenent airtime
else
    if airtime over maxFalltime
        do code here
    end if
  
    reset airtime here
end if
1 Like

Thanks for your reply!

Turns out it was a stupid error in that although I set “maxFallTime” in the code, in the Unity editor it was set higher to a number that it wasn’t reaching. Silly schoolboy error there!

Anyway, I took your advice and here is the final code I ended up using, much neater thanks!

    private void FallingPlayer(){

        if (!player.controller.isGrounded)
        {
            airTime += Time.deltaTime;
            Debug.Log("Airtime = " + airTime);
        }

        else{
            if (airTime >= maxFallTime){
                Debug.Log("PLAYER SHOULD BE HURT!");
            }
            airTime = 0.0f;
        }
    }
1 Like