I’m trying to knockback the player, when i press the button.
So i did the:
if (Input.GetKeyDown(KeyCode.C))
{
rb.velocity = new Vector2(0f, 0f);
rb.velocity = new Vector2(20f, 20f);
But the movement code i have conflicts with it, i guess it overwrites the x axis force before it can even apply. When i remove this line of code, knockback works perfectly.
Here’s the movement code:
rb.velocity = new Vector2(Input.GetAxis("Horizontal") * mspeed, rb.velocity.y);
As you can see, i tried resetting the velocity in knockbacking code, but that does no effect.
Also switching them between Update() and FixedUpdate(), but to no avail.
At this point i genuinely don’t understand how that works, any explanation would be deeply appreciated.
use the AddForce method of rigidBody to change velocity (both for knockback and moving) if you want „proper“ physics behaviour where one force affects another
you override velocity every time you directly assign a value to it as you already noticed. that may be useful in some cases but not here - unless you disable player input for the duration you want the knockback to last
replace the movement code with something like this (movespeed is just the input direction * the speed) GetComponent<Rigidbody2D>().velocity = new Vector2(Mathf.Lerp(GetComponent<Rigidbody2D>().velocity.x, movespeed, accel), GetComponent<Rigidbody2D>().velocity.y);
you could also check if your velocity is larger than movespeed and not change speed at all if you are moving in that direction already