Blue03
Blue03

Reputation: 51

check if character is falling

I made this script to check if the character is falling (I need it to set up a falling animation), but it only works when it falls from very large heights. If I jump while the character is falling, "fallen" it is not printed, while it is activated when I start to fall from greater distances. Can anyone help me or indicate another way to check if it is falling?

void Update()
{
  float previousHeight = 0f;
  var currentHeight = Controller.velocity.y;
  if(Controller.isGrounded) currentHeight = 0f;
  if(currentHeight < previousHeight) print("fallen");
  previousHeight = currentHeight;
}

Upvotes: 1

Views: 1030

Answers (1)

derHugo
derHugo

Reputation: 90580

First of all in

float previousHeight = 0f;

you all the time create a new float with value 0 ... so making any checks against it and storing a value to it in the end is pretty useless.


I suspect you rather have some field already but accidentally shadowed it. It should rather be

// Renamed it to make my point below clear
private float previousVelocity;

private void Update()
{
    var currentVelocity = Controller.velocity.y;
    if(Controller.isGrounded) currentVelocity = 0f;
    if(currentVelocity < previousVelocity) print("fallen");
    previousVelocity = currentVelocity;
}

Now looking at this you will note it still makes not much sense. I renamed the variable to make my point clear: You are checking if the previous velocity is smaller than the current one. That means only you have slowed down, not necessarily that you are falling.


You either rather want to store and compare absolute positions like e.g.

private float previousHeight;

private void Update()
{
    var currentHeight = Controller.transform.position.y;
    if(currentHeight < previousHeight) print("fallen");
    previousHeight = transform.position.y;
}

or you could also simply directly use the velocity like

private void Update()
{
    var currentVelocity = Controller.velocity.y;
    if(Controller.isGrounded) currentVelocity = 0f;
    if(currentVelocity < 0f) print("fallen");
}

Upvotes: 2

Related Questions