Can't add AddForce or velocity to RigidBody2D

Hello everyone, I’m trying to get the player knockback when touching an enemy. Everything works fine, but when I try to apply force to the player nothing happens. Does anyone know what the problem might be? Here is the code:

private void Start()
   {
       Debug.Log(currentHealth);
       rb = GetComponent<Rigidbody2D>();
       playerMovement = GetComponent<PlayerMovement>();
       currentHealth = health;
       player = GameObject.Find("Player");
   }
  
 
   private void Update()
  {
      if(rb.velocity.y < 0) {
          CheckAttackHitBox();
      }
      Debug.Log(currentHealth);
      if(rb.velocity.y >= 0 && playerStompedEnemy == false)
      {
           PlayerTouchEnemy();
      }
    
      if(touchDamageTime <= 0)
      {
          knockBack = false;
      }
      if(stompTime <=0)
      {
          playerStompedEnemy = false;
      }
  }
 
private void PlayerTouchEnemy()
  {
      enemyDetected = Physics2D.OverlapBox(playerPos.position, sizeOfBox, angle, whatIsDamageable);
      touchDamageTime -=Time.deltaTime;
      if(enemyDetected != null && touchDamageTime <= 0 )
      {
         
          attackDetails.damageAmount = attack1Damage;
          attackDetails.stunDamageAmount = stunAmount;
          gameObject.transform.SendMessage("Damage", attackDetails);
          rb.AddForce(knockBackDirection);
          knockBack = true;
          touchDamageTime = 1.5f;
         
      }
  }

Where is knockBackDirection? Does it ever really hold any values?

Sorry forgot to show this in code, but knockBackDirection is a public Vector2, I made it equal to (5,2)

Throw in some Debug.Logs to make sure it is actually being called. I had this same issue with my knockback function a year or so ago. I fixed it by increasing the force. I had the problem where the force was so small that i couldnt actually see the player get knocked backed even though the function was working properly.

1 Like

You should typically use AddForce using an impulse force mode. this modifies the velocity and isn’t scaled by the time-delta.

1 Like

In fact, now I can see that the player is affected by the force that I add, but very small