Addforce for 2d game is not doing anything.
Whatever I try, addforce2D is not doing anything. Things I have tried/checked: I have tried many different knockback powers ranging from 5 to 50000. Both objects are Dynamic. Both objects have a normal collider2D, trigger collider2D, and rigidbody2D. I have Debug.Logs making sure that they are colliding, and I do receive those messages every time they collide. The mass of the enemy, the object to get knocked back, is 0.1. I have tried changing that value too. The mass of the weapon, the object that causes the knockback, is 1. I have no idea what is wrong. If anybody can help it would be greatly appreciated.
public class KnockBack : MonoBehaviour { public float knockbackStrength;
private void OnTriggerEnter2D(Collider2D collision)
{
Rigidbody2D rb = collision.GetComponent<Rigidbody2D>();
if(rb != null && collision.tag == "Enemy")
{
Debug.Log("I have collided with an enemy!");
Vector3 direction = collision.transform.position - transform.position;
Debug.Log("I forced an enemy!");
rb.AddForce(direction.normalized * knockbackStrength, ForceMode2D.Impulse);
}
}
}
What happens if you Log the result of direction.normalized * knockbackStrength
? If it's a non-zero vector, my guess is that there's something else nullifying the force? For example, are you setting the Rigidbody's velocity to zero in fixed update? Unity by default does things in this order:
Fixed update executes.
Physics simulation runs a step.
Collision/Trigger messages are send.
That means the physics simulation doesn't run between OnTriggerEnter2D and the next FixedUpdate; so, if you're doing something like setting the velocity in FixedUpdate, it could nullify any force added in the physics callbacks.
Your answer
Follow this Question
Related Questions
Why/How 2d tower of blocks collapse? 0 Answers
Rigidbody2D.AddForce inconsistent force amount 0 Answers
2D Physics movement system is creating unexplained random variations. 0 Answers
How to make arrows fly to user mouse position? 0 Answers
How can I slow the movement of a single rigidbody2D? 2 Answers