- Home /
How to detect if player is falling without rigidbody?
I'm trying to detect if my player is falling by tracking if his Y position is decreasing, however it doesn't seem to be working. I'm keeping track of his latest Y position in LateUpdate but it doesn't make a difference; is there a better way to tell if his Y position is decreasing or better yet get the decrease rate?
void Update()
{
if(!player.GetComponent<GroundedCharacterController>().isGrounded){
if(cineTransposer.m_FollowOffset != fallingOffset && player.transform.position.y < lastYPos){
StartCoroutine(LerpToFallingOffset());
}
}else{
if(cineTransposer.m_FollowOffset != standingOffset){
StartCoroutine(LerpToStandingOffset());
}
}
}
void LateUpdate(){
lastYPos = player.transform.position.y;
Debug.Log("last y pos is " + lastYPos);
}
Answer by CodesCove · Nov 24, 2021 at 07:50 PM
You can calculate the dropping speed inside Update. Just calculate the difference in in position divided by the difference in time between the frames (Update is run once per frame) and you get speed.
Pseudocode:
speed = (player.transform.position.y - lastPosition) / Time.deltaTime;
lastPosition = player.transform.position.y; //store the position for the next frame calculation;
PS, you cannot get any difference in position between Update and LateUpdate (unless you specially move in object in both.. however this would not make any sense because this extra movement wouldn't be rendered anyway)
I've added the below to Update but it always returns "player y speed is 0" even if I'm jumping or falling
lastYPos = player.transform.position.y;
float speed = (player.transform.position.y - lastYPos) / Time.deltaTime;
Debug.Log("player y speed is " + speed);
Is that what you meant?
lastYPos = player.transform.position.y; goes after, not before the speed calculation.
Also it's better to define speed as class level variable if you are using it somewhere else than in the Update and after the calculation.
Thank you, I had better luck when adding it to FixedUpdate()!