Knockback player on collision
I want to create a game where if my player collides with an enemy the player gets knocked back/ pushed back. I've looked on Google and tried different codes but none of them meet my satisfaction. Most of the codes I used included AddForce. I want it to be something like this:
Thank You!
Are you using Character Controller or Rigid Body to develop your characters?
Answer by lloladin · Nov 14, 2015 at 02:44 PM
i normally just use velocity like this
gameobject.GetComponent<Rigidbody2D>().velocity = new Vector2 (x,y);
the only problem with this is that the object will move for a while after being knocked back a way to solve that would be use a timer to change the duration of the knockback or like i do simply change the velocity to 0 when the object hits the ground if the object is being knockedbacked so make a bool that you check/uncheck depending on whether the object is being knocked back
Code for the object that knocking things back
public bool knockedBack
void OnTriggerEnter2D (Collider2d other)
{
other.GetComponent<Rigidbody2D>().velocity = new Vector2 (x,y);
knockedBack = true
}
and for the object thats being knocked back
public bool grounded
if (grounded && GetComponent<Other Script>().knockedBack == false)
{
GetComponent<Rigidbody2D>().velocity = new vector 2 (0,0)
}
hope this help
Answer by Statement · Oct 31, 2015 at 01:03 PM
So I don't know which methods you've used but it looks from the picture that a simple AddForce won't cut it because you want rotation as well. Use AddForceAtPosition and set the position slightly off center to give it some spin. Try using ForceMode2D.Impulse.
For 3D, see the Rigidbody docs. The methods are called the same.
I also have an example 2d playable demo/full source that uses AddForceAtPosition to simulate top down wheel physics in this answer.