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

Player bounce back when hit

Discussion in '2D' started by Syzo, Dec 19, 2016.

  1. Syzo

    Syzo

    Joined:
    Nov 1, 2016
    Posts:
    17
    Hello community!

    I'm currently looking for the most efficient way to make my Player gameObject bounce backwards everytime it receives damage.


    Thank you in advance!
     
  2. Eyeshock

    Eyeshock

    Joined:
    Sep 7, 2012
    Posts:
    60
    1) Flag for damage so they can't take damage immediately again
    2) Take away player controls for bounce back
    3) Identify damage source
    4) Move character away / push rigidbody in opposite direction
    5) Clear Flags
    6) Restore Player Control

    Here's code I used to do it in 2D for multiplayer; Good luck
    Code (csharp):
    1.  
    2.    public void Damaged(Transform damageSource){
    3.  if (!invincible) {
    4.  anim.SetTrigger ("TriggerDamage");
    5.  Debug.Log ("Monsterisdamaged!");
    6.  StartCoroutine (FlashSprite (damageSource));
    7.  tno.Send ("TriggerDamage", Target.Others);
    8.  }
    9.  }
    10.  [RFC]
    11.  protected void TriggerDamage ()
    12.  {
    13.  anim.SetTrigger("TriggerDamage");
    14.  }
    15.  IEnumerator FlashSprite(Transform damageSource) {
    16.  invincible = true;
    17.  animationObj.GetComponent<SpriteRenderer>().color = Color.red;
    18.  rbody.velocity = new Vector2((transform.position.x - damageSource.position.x) * 25 , rbody.velocity.y);
    19.  
    20.  //delayspecified amount
    21.  yield return new WaitForSeconds(recoveryTime);
    22.  health--;
    23.  animationObj.GetComponent<SpriteRenderer>().color = Color.white;
    24.  invincible = false;
    25.  if (health == 0)
    26.  HeroHasDied ();
    27.  }
    28.  
    29.