Lock diagonal movement with Joystick Input

Hi everybody !

I’m doing a 2D on android and i want to use a joystick to move my player in 4 direction.

but whith my code, my player can move to 8 direction
So i want to know if i can lock the diagonal direction?

Here my code :slight_smile:

 if (CrossPlatformInputManager.GetAxis("Horizontal") > 0.5)
            {
                // vector2 move code

            }

            if (CrossPlatformInputManager.GetAxis("Horizontal") < -0.5)
            {
             
  // vector2 move code

            }

            if (CrossPlatformInputManager.GetAxis("Vertical") < -0.5)
            {
             
  // vector2 move code

            }

            if (CrossPlatformInputManager.GetAxis("Vertical") > 0.5)
            {
             
  // vector2 move code

            }

Thanks for reading me !
Have a good day !:slight_smile:

might want to consider GetAxisRaw to ensure it’s always -1…1

Thx for youre answer !
So if I change “GetAxis” by “GetAxisRaw” it will work? With mathf. Round?

Thx for your help !

you can do it like this :

    public Rigidbody2D rb;
    public float speed = 4f;
    public Joystick joystick;
    Vector2 movement;
    float horisontal =0f;
    float vertical =0f;


    // Update is called once per frame
    void Update()
    {
        if (joystick.Horizontal >= 0.1)
        {
            horisontal = 1;
        }
        if (joystick.Horizontal <= -0.1)
        {
            horisontal = -1;
        }
        if (joystick.Vertical >= 0.1)
        {
            vertical = 1;
        }
        if (joystick.Vertical <= -0.1)
        {
            vertical = -1;
        }
        if(Mathf.Abs(joystick.Horizontal) > Mathf.Abs(joystick.Vertical))
        {
            vertical = 0;
        }
        else
        {
            horisontal = 0;
        }
        movement.x = horisontal;
        movement.y = vertical;
        Debug.Log("h: " + horisontal + "  v: " + vertical);
    }

    private void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
    }
2 Likes