Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Damage from a fall

Discussion in 'Scripting' started by martincz26, Dec 20, 2022.

  1. martincz26

    martincz26

    Joined:
    Jan 28, 2021
    Posts:
    13
    Hi, I have the following code

    Code (CSharp):
    1.  
    2.     [SerializeField] private float _Gravity = 8f;
    3.     [SerializeField] private float _JumpHeight = 2f;
    4.     [SerializeField] private float _FallDamageThreshold = 5f;
    5.     [SerializeField] private float _FallDamegeMultiplier = 2f;
    6.     [SerializeField] private float _Health = 100f;
    7.     [SerializeField] private float _MaxHealth = 100f;
    8.  
    9. private bool isDead()
    10.     {
    11.         if (_Health < 0)
    12.         {
    13.             _Health = 0;
    14.             return true;
    15.         } else
    16.         {
    17.             return false;
    18.         }
    19.     }
    20.  
    21.  
    22.     private void FixedUpdate()
    23.     {
    24.         if (!isDead())
    25.         {
    26.          
    27.             float fall = Vector3.Distance(_CharacterController.velocity, velocity);
    28.             Debug.Log(fall);
    29.  
    30.             if (fall > _FallDamageThreshold && _CharacterController.isGrounded)
    31.             {
    32.                 _Damage = fall * _FallDamegeMultiplier;
    33.                 _Health -= _Damage;
    34.             }
    35.             velocity = _CharacterController.velocity;
    36.             Debug.Log("HP:" + _Health + ", Damage:" + _Damage);
    37.         }
    38.     }
    The code is part of the Player script that controls the player. And it's supposed to cause some damage to the player when falling from a height greater than the height set in the _FallDamageThreshold variable, it's not "yet" worked out. And it actually works pretty well, that is, only until the player jumps on the plane, in which case damage is taken, and quite high damage at that. Could someone help me modify the code to make it work properly?
     
  2. FlashMuller

    FlashMuller

    Joined:
    Sep 25, 2013
    Posts:
    449
    Your fall-damage is actually accelleration-damage. Distance is always positive and you check your old velocity against your current velocity. So jumping up will be handled just as falling down.
    I'd simply use the y-component. If it's negative your falling. If it's exceeding a certain value you are falling to fast.