- Home /
 
Adding knockback to 2D multiplayer game
Hi there. I'm making a 2D multiplayer run-and-shoot game where the two players need to shoot each other. Once a player loses all its lives, the other player wins the game. This is all working fine, but it's time to polish. I want to add a knockback effect on each player, so that when a player collides with either a bullet or one of the monsters patrolling the platforms, a knockback is applied into the same direction that what hit it was heading towards.
All the code that needs to be provided (I think) is this:
 public void HurtP1()
     {
         shouldShake = true; //this is just a screen shake
         P1Life -= 1;
 
         P1Flasks();
 
         hurtSound.Play();
 
              Answer by mrlekova · Dec 07, 2019 at 04:39 PM
Ok, so far I've added the following, but it doesn't work optimally. The character just jumps when hit. In the player controller script:
     public float knockback;
     public float knockbackLength;
     public float knockbackCount;
     public bool knockFromRight;
 
 void Update()
     {if (knockbackCount <= 0)
         {
             rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
         }
         else
         {
             if (knockFromRight)
                 rb.velocity = new Vector2(-knockback, knockback);
             if (!knockFromRight)
                 rb.velocity = new Vector2(knockback, knockback);
                 knockbackCount -= Time.deltaTime;
             }
 
 
         if (Input.GetKey(left))
         {
             rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
         }
         else if (Input.GetKey(right))
         {
             rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
         }
         else
         { 
             rb.velocity = new Vector2(0, rb.velocity.y);
         }
 }
 
               In the bullet script:
     void OnTriggerEnter2D(Collider2D other) //if the laserbeam interacts (collides) with anything else, just make it vanish
     {
         if(other.tag == "Player1")
         {
             FindObjectOfType<GameManager>().HurtP1();
             var player = other.GetComponent<P1Controller>();
             player.knockbackCount = player.knockbackLength;
 
             if (other.transform.position.x < transform.position.x)
                 player.knockFromRight = true;
             else
                 player.knockFromRight = false;
         }
 
              Your answer
 
             Follow this Question
Related Questions
Network Sync Bullet 2D 0 Answers
Spawning objects in multiplayer game 1 Answer
Lag Compensated Projectile 0 Answers
Problem with gun rotation after flipping character (2D) 1 Answer