AddForce not working in negative directions

40 views Asked by At

I am coding a 2d rpg and was adding a dash mechanic, but for some reason whenever the facing value is (-1, 0), (-1, -1), or (0, -1) the force doesn't get applied. It works perfectly fine in all other directions, and I have used debug.log to see the velocity output which is correct. it seems like it getting canceled out but I don't know what is causing it. Here is my code for adding the force.

if (Input.GetKeyDown(KeyCode.C) && !exhausted)
{
    if (stamina >= dashStaminaCost)
    {
        staminaTimer = 0;
        stamina -= dashStaminaCost;
        body.AddForce(facing * dashForce, ForceMode2D.Impulse);
    }
}
2

There are 2 answers

0
GoncaloN On

If you suggest that some of the facing directions cause improper application of force, this could imply that, in those instances, the computation for “facing” vector is wrong.

To ensure uniform force application no matter the way:

The facing vector should be normalized so it has a length of 1 unit.

You can normalize it with something like this:

if (Input.GetKeyDown(KeyCode.C) && !exhausted)
{
    if(stamina >= dashStaminaCost)
    {
        staminaTimer = 0;
        stamina -= dashStaminaCost;

        // Normalize the facing vector
        Vector2 facingDirection = facing.normalized;

        // Apply force using the normalized facing direction
        body.AddForce(facingDirection * dashForce, ForceMode2D.Impulse);
    }
}
1
Maddox Fox On

It was actually a problem with my function for movement, that only stopped keyboard input if the velocity was more than the move speed, and did not take into account if it was below. here is the original code

if (body.velocity.x < moveSpeed && body.velocity.y < moveSpeed){My Code}

here is my fixed code

if (body.velocity.x < moveSpeed  && body.velocity.x > - moveSpeed && body.velocity.y < moveSpeed && body.velocity.y > -moveSpeed)
        {My Code}