Why doesn't my knockback function apply force to it's target?
I'm making a 2-D game, and thought I'd try my hand at a simple knockback script using ForceMode2D and AddForce. The problem is, when my character hit his target, most of the time the force isn't applied, and if it is applied, it will be on the second or third hit in my combo string. Here is my code: public int dmg = 0; public float knockForce = 0f;
void OnTriggerEnter2D(Collider2D target) // Collider2D
{
if(target.tag == "Player") //may have to be other.tag != "Player") if it doesnt work
{
// knockback
Vector2 directionVector = target.transform.position - transform.position;
directionVector.Normalize();
Rigidbody2D targetPlayerBody = target.GetComponentInParent<Rigidbody2D>();
ForceMode2D mode = ForceMode2D.Impulse;
targetPlayerBody.AddForce(directionVector * knockForce, mode);
Debug.Log(directionVector);
//damage
Debug.Log("Hit!!");
charHealth targetPlayerHealth = target.gameObject.GetComponentInParent<charHealth>();
targetPlayerHealth.TakeDamage(dmg);
I've set up my animations in mecanim with animation events to control when damage and knockback force is applied, and how much is sent through. I know that the damage is being sent, so I figured knockForce was being sent through as well. I've now confirmed through the editor that the force is being applied to the attack's properties, but it's still having next to no effect on it's target.
I'm kinda, sorta really new to this, and although I can code a little C#, I'm obviously just a beginner, so any and all help is greatly appreciated.
Answer by KBEK · Jun 30, 2016 at 06:06 PM
It looks like you set knockForce = 0f at the beginning of your code. This would make it so no force is getting added.