transform.right doesn't work, but transform.up works for Dash script

Hello. I have following code for handling player walking, jumping & dashing:

public class PlayerMovement : MonoBehaviour
{
   [HideInInspector]public Rigidbody2D rb;
   public float runSpeed = 5f;
   public float jumpSpeed = 3f;
   public Joystick joystickRun;

   [HideInInspector]public float moveInputH;
   [HideInInspector]public float moveInputV;
   public float dashSpeed;
  
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate() {
        if(joystickRun.Horizontal >= .2f){
            moveInputH = runSpeed;
            transform.eulerAngles = new Vector3(0,0,0);           
        }
        else if(joystickRun.Horizontal <= -.2f){
            moveInputH = -runSpeed;
            transform.eulerAngles = new Vector3(0,180,0);      
        }
        else{
            moveInputH = 0f;
        }
        rb.velocity = new Vector2(moveInputH, rb.velocity.y);
    }
    void Update()
    {    
        if(Input.GetKeyDown(KeyCode.Space)){
           Jump();          
       }

        if(Input.GetKeyDown(KeyCode.M) ){
            Dash();          
        }
    }
  
    void Jump(){
        rb.velocity = Vector2.up * jumpSpeed;
    }
    void Dash(){
        rb.velocity = transform.right * (runSpeed * 6);
        Debug.Log("Dash worked...");
    }
}

The problem is that in Dash() method transform.right doesn’t work at all, but if I replace it with transform.up, it works and Player dashes upwards. I tried using rb.AddForce(transform.right * dashSpeed * 400); Instead of transform.right, but the result is different → Player literally teleports instead of dashing, that’s why I stopped using it.
Do you have any ideas, why transform.up works, but transform.right doesn’t work?

Line 30 is ALWAYS setting the velocity, so Dash and Jump will do nothing (or almost nothing, perhaps just for a single frame).

You are also mixing and matching doing physics in Update() and FixedUpdate(). It is a GOOD thing you are doing GetKeyDown() in Update() (in fact it is required!), but you should set flags that these inputs happened, then act upon them in FixedUpdate().

1 Like

As Kurt is saying, your issue is you overwrite velocity all over the place instead of modifying velocity. On line 30 you are overwriting the X velocity with the contents of moveInputH, while keeping the Y velocity. So everywhere else you set velocity will always lose its X component.

This is one reason Unity warns against setting velocity directly instead of just adding forces. You can easily end up in issues like this.