0
votes

Or rather I should say, "EFFECTIVELY disabling diagonal movement".

There are plenty of Q/As online about this, but I keep encountering the same problem: When moving horizontally (left, for example), I can override the current direction and start moving vertically (by pushing up), which is what I want. But it does not work the other way around! Vertical movement can not override horizontal movement.

void Update () {

         float h = Input.GetAxis("Horizontal");
         float v = Input.GetAxis("Vertical");
          ManageMovement(h, v); 
}    

void ManageMovement(float horizontal,float vertical) {

        if (vertical != 0f) {
                horizontal = 0f;
                Vector3 movement = new Vector3 (horizontal, vertical, 0);
                GetComponent<Rigidbody2D> ().velocity = movement * speed;
                return;
            } 

        if (horizontal != 0f) {
            vertical = 0f;
            Vector3 movement = new Vector3 (horizontal, vertical, 0);
            GetComponent<Rigidbody2D> ().velocity = movement * speed;
            return;

        } else {
            Vector3 noMovement = new Vector3 (0, 0, 0);
            GetComponent<Rigidbody2D> ().velocity = noMovement;
        }
    }

If I reverse the order of these if() statements, it reverses the problem. So, that's a clue. But I'm not a great detective. I would love some help!

2

2 Answers

0
votes

try to add else statement to ManageMovement method:

void ManageMovement(float horizontal,float vertical) {

    if (vertical != 0f) {
            horizontal = 0f;
            Vector3 movement = new Vector3 (horizontal, vertical, 0);
            GetComponent<Rigidbody2D> ().velocity = movement * speed;
            return;
        } 

    else if (horizontal != 0f) {
        vertical = 0f;
        Vector3 movement = new Vector3 (horizontal, vertical, 0);
        GetComponent<Rigidbody2D> ().velocity = movement * speed;
        return;

    } else {
        Vector3 noMovement = new Vector3 (0, 0, 0);
        GetComponent<Rigidbody2D> ().velocity = noMovement;
    }
}
0
votes

Use Input.GetAxisRaw instead of GetAxis.

GetAxis returns a float on a scale from -1 to 1. How quickly it returns to 0 depends on the axis settings. If you set gravity to a very high number, it will return to 0 more quickly. If you set sensitivity to a very high number, it will go to -1 or 1 more quickly.

So depending on these settings your function ManageMovement will be called multiple times with gradually changing values for horizontal and vertical.

The inputs over times could look something like this:

Update #1: ManageMovement(0.2, 1.0)
Update #2: ManageMovement(0.3, 0.9)
...
Update #N: ManageMovement(1.0, 0.0)

So when you check if vertical != 0, it will keep being non-zero until it has actually reached 0, and then for all those updates before that you set horizontal to 0.

GetAxisRaw is not smoothed in this way.