This site uses strictly necessary cookies. More Information

X- Home /

**Question**by spirachi77 · Jan 15, 2019 at 05:02 AM · rigidbody2drigidbody.addforceknockbackmathf.sinmathf.cos

# The knockback function I made is pushing me to the left

this is my knockback function the takes in an angle, force, and hitstun. The rigidbody's velocity is set to zero before the force is applied, sin for y and cos for x and then multiplied by force. Y is multiplied by the gravity scale in the rigidbody. The problem is that it pushed the player to the left, for example if the angle is 90, the player should be sent straight up, but its pushed upwards and to the left. Any help is appreciated.

```
private void KnockBack(float ang, float force, float stun)
{
rb.velocity = new Vector2(0,0);
rb.AddForce(new Vector2((Mathf.Cos(ang) * Mathf.PI) / 18 * force * 100, (Mathf.Sin(ang) * Mathf.PI) / 18 * force * 100 * 5));
hitStun = stun;
state = "stunned";
}
```

Good day. I prettend to help you, but...

If you commence talking about angles and directions, we need a reference point or something. "for example if the angle is 90" .. from where? $$anonymous$$ake it super clear please.

Can you make 2 basic draws to easy understand what is happening and what you want to get?

PD: just a tip, to reduce to 0 a vector, you can write this

```
rb.velocity = Vector2.zero;
```

Bye!

tree tips

1) the `$$anonymous$$athf.Cos`

and `$$anonymous$$athf.Sin`

the angle is expresed on radians, not degrees, so please convert `ang`

to radians `ang = ang*$$anonymous$$athf.PI/180f`

u can do it before add force, to evade do it twice... and is `180`

, not `18`

2) whatever if u want do it inside Addforce, calculate it *before* do the cos calculus, so put the conversion to the angle *inside* the function `mathf.cos`

some like `mathf.cos(ang*$$anonymous$$athf.PI/180)*force*100`

3) on the calculus of addforce u multiply the `y`

component of the vector 5 times more than the x component... have a `* 5`

there, the float aren't precise so, the calculus of y component give aprox 0.00019... multiplied by 5 and not correctly divided (by 18) can be a considerable force

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

Rigidbody.addforce not working with prefab 1 Answer

AddForce gradually decreasing 0 Answers

How do I get ForceMode2D.Impulse to work? 2 Answers

rigidbody2d.addforce for is not working for the x axis 0 Answers