4 Way Movement Using Joystick Input

Hi All,

I’m trying to write a C# script for character movement that only allows my character to move in 1 of 4 directions at a time (up, down, left, right).
The challenge is that I want this to use joystick input instead of keyboard.

I currently have a script which I found on these forums which works perfectly, except for the fact that it allows 8 way (ie. can move diagonally) movement instead of just 4.

Here is the script I’m currently using. Any tips on how I can update it to restrict diagonal movement would be great.

public class newMove : MonoBehaviour {

    private float speed = 1f;
    public Transform playergraphic;

    // Update is called once per frame
    void FixedUpdate()
    {
        Movement();
    }

    void Movement()
    {

        //Player object movement
        float horMovement = Mathf.Round(Input.GetAxis("Horizontal"));
        float vertMovement = Mathf.Round(Input.GetAxisRaw("Vertical"));

        transform.Translate(transform.right * horMovement * Time.deltaTime * speed);
        transform.Translate(transform.forward * vertMovement * Time.deltaTime * speed);

        //Player graphic rotation
        Vector3 moveDirection = new Vector3(horMovement, 0, vertMovement);

        moveDirection.Normalize();

        if (moveDirection != Vector3.zero)
        {
            Quaternion newRotation = Quaternion.LookRotation(moveDirection);
            playergraphic.transform.rotation = Quaternion.Slerp(playergraphic.transform.rotation, newRotation, Time.deltaTime * 5);
        }
    }
}

Late but works perfectly for me.

`
//Update
_InputDir = joystick.GetInputDirection(); // Joy Stick input
inputX = _InputDir.x;
inputY = _InputDir.y;

if (Mathf.Abs (inputX) > Mathf.Abs (inputY)) {
inputY = 0;
} else {
inputX = 0;
}`

The simplest way I can think of to do this would be to discard one of the inputs.

So, you read in your horizontal and vertical axis as you are now, then you check the magnitude of each value, whichever axis has the largest absolute value gets used, and the other gets set to zero, then you apply those values to your movement.