Nao
Nao

Reputation: 29

Addforce won't knockback my player character

I'm trying to add knockback to my player, but he won't move. I know the function is correctly called and the if a statement is functional, as he will still take damage, but the player won't move at all. Weirdly, if I put the addForce somewhere else (Like in the update() method), it will work, but not in this scenario.

Some help would be greatly appreciated

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
        {
            TakeDamage(-20, 21);
            theRB.AddForce((collision.transform.position - transform.position).normalized * 100, ForceMode2D.Impulse);
        }
    }

Here is what the Rigidbody looks like if it helps:

Upvotes: 1

Views: 593

Answers (2)

Nao
Nao

Reputation: 29

Ok, so I figured out the answer. The problem lies in the way I managed movement in my Movement() function. To create movement, I used this line :

theRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * playerSpeed;

Apparently, velocity doesn't really work well with AddForce, for reasons I am not capable of explaining, as my understanding of Unity is still limited. I'll need to figure out a better way to manage movement, and I'll edit this post once I figure it out in case someone made the same mistake as me.

EDIT : So, turns out I've been looking for weeks, and didn't find anything. My final solution was to use a LERP instead of Addforce(), and just forget about physics alltogether.

Upvotes: 1

Seth Setse
Seth Setse

Reputation: 345

Hey I think the issue here is with your use of

(collision.transform.position - transform.position)

I would instead calculate the direction using the contact point of the collision and save that in a Vector. Then normalize that vector and multiply by -1 to launch the player in the opposite direction. Here's some sample code:

Vector2 dir = collision.contacts[0].point - transform.position;
     // Flip the vector and normalize
     dir = -dir.normalized;
     // Apply Force
     theRB.AddForce(dir * 100, ForceMode2D.Impulse);

Upvotes: 2

Related Questions