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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Resolved Why does force.impulse keep applying forever after the attack?

Discussion in 'Scripting' started by unity_gNikEk9EZr6y4w, Apr 10, 2023.

  1. unity_gNikEk9EZr6y4w

    unity_gNikEk9EZr6y4w

    Joined:
    May 27, 2020
    Posts:
    2
    Hello, I am new to UnitY and can't find the answer to my question.
    My attack script is made so if the attack hits then it sends the enemy's take damage script: the damage of the player, the possition of the player and the knockback force.
    The force keeps applying in the same direction as the original knockback direction and does not update if i move around.
    For the enemy ai i used Nav Mesh Agent.

    Attack script
    Code (CSharp):
    1.  public void attack()
    2.     {
    3.         if(Time.time >= playerAttackSpeedCounter )
    4.         {
    5.             Collider[] colliderArray = Physics.OverlapSphere(attackPoint.position, attackRange, hittable);
    6.             foreach (Collider collider in colliderArray)
    7.             {
    8.                 collider.GetComponent<EnemyHealth>().takeDamage(playerDamage, transform.position, knockback);
    9.            
    10.             }
    11.        
    12.             playerAttackSpeedCounter = Time.time + playerAttackSpeed;
    13.             attackAnim.Play(attackName);
    14.         }
    15.  
    16.     }
    Takdemage script
    Code (CSharp):
    1.     public void takeDamage(float playerDamage, Vector3 playerPos, float knockback)
    2.     {
    3.         //damage
    4.         enemyHealth -= playerDamage;
    5.  
    6.         //knockback
    7.         Vector3 knockbackDirection = transform.position - playerPos;
    8.         rb.AddForce(knockbackDirection.normalized * knockback, ForceMode.Impulse);
    9.     }
     
    Last edited: Apr 10, 2023
  2. unity_gNikEk9EZr6y4w

    unity_gNikEk9EZr6y4w

    Joined:
    May 27, 2020
    Posts:
    2
    I did not have drag on my Enemy object. I put the drag to 1 and now it works as i wanted to.