2D Knockback problem
I'm having problems with knockback function in a top-down game. when the enemy hits the player Horizontally, when this happens, the player just "teleport" instead of making a smooth move.
i'm using this code:
     private void OnCollisionEnter2D(Collision2D col)
         {
             if (col.gameObject.tag == "Player")
             {
                 GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerStatus>
                 ().takeDamage(damage,this.transform);
             }
         }
 
    public void takeDamage(float damage,Transform obj)
     {
         Vector2 direction = (obj.transform.position - transform.position).normalized; 
         GetComponent<Rigidbody2D>().AddForce(-direction * force);
     }
 
               where "obj" is the enemy transform... I made some tests and when I just use the addforce (with fixedUpdate function) to the left or right, the force is smaller than when it does vertically.
               Comment
              
 
               
              Answer by Elxungo · Sep 05, 2018 at 07:08 PM
Hi @ruan1131, I know that question is old but I fix that with a IEnumerator.
I have this on the script of the enemy
 void OnCollisionEnter2D(Collision2D other){
 
     if(other.gameObject.tag == "Player"){
 
         //make damage to the player
         player.setHealth(player.getHealth() - this.damage);
 
         //make the nockback
         StartCoroutine(player.Knockback(0.02f, 350f, this.transform));
 
     }
 
 }
 
               and this on the Player Script, I use IEnumerator to make the duration of the knockback with a while.
 public IEnumerator Knockback(float knockDur, float knockbackPwr, Transform obj){
 
     float timer = 0;
 
     while( knockDur > timer ) {
         timer += Time.deltaTime;
         Vector2 direction = (obj.transform.position - this.transform.position).normalized;
         rbody.AddForce(-direction * knockbackPwr);
     }
 
     yield return 0; 
 
 }
 
              Your answer