- Home /
Fall damage
Hello there community. I am trying to make a 2D puzzle platformer but I am having some problems with my "fall damage" script. The code works, sometimes... I have no idea why it doesn't work all the time.
When a player falls from a high platform and get a vertical velocity of over 80 I assign the variable lethalSpeed to true, the problem is that you can shift gravity while in mid-air so even if you at one point during the airtime have lethalSpeed you might survive if you gravity shift and land on a platform before you reach lethalSpeed.
I have been trying to debug the code with Debug.Log, but it seems it doesn't enter for example respawnI() even if the conditions in the if-statement are met(should be met).
I would apreciate any feedback figuring this out or if I can improve anything. And as I said, it works sometimes.
private void checkPlayerState()
{
if (!grounded)
{
currentSpeed = Mathf.Abs(rigidbody2D.velocity.y);
if (currentSpeed > 80f)
lethalSpeed = true;
else
lethalSpeed = false;
}
if (grounded && lethalSpeed)
{
respawn ();
}
}
private void respawn()
{
gameObject.transform.position = currentCheckPoint;
currentSpeed = 0;
lethalSpeed = false;
}
EDIT: Problem solved!
Answer by MrSoad · Oct 11, 2014 at 03:21 PM
It could be that you are hitting the ground causing your speed to drop below 80f before your death check kicks in. This will reset your lethalSpeed to false. So you are on the ground but not dead. Maybe switch the Death check "if (grounded && lethalSpeed)" section to before the "if (!grounded)" section to avoid this.
I would prob be doing this sort of state change check in the on collision function. This way it will trigger when the event happens rather than when you code activates in Update or wherever you are calling it from. Which could affect you "grounded" state check.
I have used Debug.Log(currentSpeed) and it shows that the speed is higher than the threshold and I only change the value of currentSpeed while in the air. Also the character hits the ground after the groundcheck does, so currentSpeed is never decreased before jumping again.
I could do with seeing more code. If you are not calling checks from on collision events then your actual character state may be different from you codes current best information regarding your character state. Post more code and I will have a better look for you.
Layer$$anonymous$$ask whatIsGround;
void Update()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundedRadius, whatIsGround);
checkPlayerState ();
}
This is the groundcheck, I have used this type of groundcheck throughout my project, but as you say "onCollisionEnter2D" might be a better choice in this situation
Sorry for the code formatting, any help or advice on posting code better is very welcome. I don't see a 101010 button anywhere, or any buttons or formatting options(using Firefox). Please put me on the right path if you have a moment thanks!
Your answer