Search Unity

knockback for Rigidbody2D

Discussion in '2D' started by cmb24, Nov 21, 2013.

  1. cmb24

    cmb24

    Joined:
    Oct 3, 2013
    Posts:
    13
    Hey all,

    Ive been struggling with this for a few hours now...

    I want want to add a knockback effect like Terraria when either the player or enemy is struck by either. Right now I have a knock back..but its lame and not giving expected results.

    So my enemy moves like this...

    Code (csharp):
    1. // ... dir is 1 or -1 depending on which side the player is on...this makes my enemy
    2. //follow the player
    3. rigidbody2D.velocity = new Vector2(maxSpeed*dir, rigidbody2D.velocity.y);  

    and when he gets hit by the player ....

    Code (csharp):
    1.   if(knockBack){
    2.                 if(fromLeft)
    3.                     rigidbody2D.AddForce(new Vector2(3000,100));
    4.                 else
    5.                     rigidbody2D.AddForce(new Vector2(-3000,100));
    6.  
    7.                 knockBack=false;
    8.             }

    You may think to yourself, "Wow. Such force." but I have cranked this up to 100,000 and the enemy goes back .5 inches on the screen. I think it has something to do with the enemy's velocity, how it moves rather. All the directions and stuff are working...I just don't know why this knock back is lame. Thoughts?
     
  2. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    perhaps your unit sizes are pathetically huge like oh, 1 pixel = 1 meter, which is silly.
     
  3. cmb24

    cmb24

    Joined:
    Oct 3, 2013
    Posts:
    13
    I think my unit size is around the default. For example when I make a cube..all my sprites and stuff are relatively the same size.
     
  4. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    A strange problem as your scales are great. There is no ForceMode parameter in this version of the physics. So you should be able to use rigidbody2D.velocty = new Vector2(x,y); instead. This would give you what you're looking for, for an immediate hit.
     
  5. cmb24

    cmb24

    Joined:
    Oct 3, 2013
    Posts:
    13
    That seems to do the trick for now. I tried that before but I guess I wasn't using high enough values. I am setting the velocity every fixed frame so it was just overwriting the knockback so fast the the values I had in there before didnt get to take effect. But this does seem to work..and I'm sure I will have to mess with the values a bunch of times.

    Thanks for the help.
     
  6. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,481
    This is coming (along with a whole bunch of force methods) in a future release, it didn't make it into 4.3 unfortunately.