c# – Unity 2d forwards and backwards instead of left and right

You’re going to want to use transform.up instead of transform.forward, as transform.forward doesn’t really exist in 2D. Transform.forward would move the ship along the ships z axis, whereas transform.up keeps the movement relative to the “forwards” direction of the ship. You will also want to change dir to just a Vector2, with all values the same (as you might want to move the ship along the x axis, not just the y axis), so

if (inputU)
            {
                dir = Vector2.one;
            }

or just a float:

if (inputU)
                {
                    dir = 1;
                }

After implementing these changes, the code should look like this:

    public float moveSpeed;
    public float smoothing;

    private bool inputU;
    private bool inputD;
    private bool inputL;
    private bool inputR;
    public float rotationSpeedL;
    public float rotationSpeedR;

    private float dir;
    private Rigidbody2D rb;



    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        
    }

    void FixedUpdate()
    {
        inputU = Input.GetKey(KeyCode.W);
        inputD = Input.GetKey(KeyCode.S);
        inputL = Input.GetKey(KeyCode.A);
        inputR = Input.GetKey(KeyCode.D);

        if (inputU && inputD || !inputU && !inputD)
        {
            dir = dir / 2;
        }
        else
        {
            if (inputU)
            {
                dir = 1;
            }
            if (inputD)
            {
                dir = -1;
            }
        }
        if (inputL)
        {
            transform.Rotate(0,0,rotationSpeedL);
        }
        if (inputR)
        {
            transform.Rotate(0,0,rotationSpeedR);
        }
        Debug.Log(transform.forward);
        rb.velocity = Vector2.Lerp(rb.velocity, dir * moveSpeed * transform.up, smoothing);    
        
}

Read more here: Source link