- Home /
Struggling to smoothly disable diagonal movement
Here is my code:
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public Rigidbody2D rb;
public Animator animator;
Vector2 movement;
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
movement = movement.normalized;
if (movement.x != 0)
{
movement.y = 0;
}
else if (movement.y != 0)
{
movement.x = 0;
}
animator.SetFloat("Horizontal", movement.x);
animator.SetFloat("Vertical", movement.y);
animator.SetFloat("Speed", movement.sqrMagnitude);
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
With this code, the diagonal movement is restricted, but if you're pressing up or down and then press left or right, it will move in that direction, which is the way I want it to work. However, if you're pressing left or right and then press up or down, the player continues moving left/right. I know this happens because of the order of the if statements: if I switch the movement.x in the first if statement with movement.y (and change everything else accordingly), then the same problems persists with the other directions.
Any suggestions on how to get the most recent key to be the direction the player continues in, even if they'd already been moving in a particular direction?
Answer by mathemaat · Sep 23, 2019 at 11:38 AM
What about adding a private Vector2 previousMovementVector;
to your class, that you update at the end of every step. You may also need
private enum MovingDirection { None, Horizontal, Vertical };
private MovingDirection currentMovingDirection;
Then, by comparing your new movement to the old movement vector, you should be able to determine the new moving direction.
I don't have the code ready for you, but I think you will manage. Maybe you don't even need both of my suggestions.
Your answer
![](https://koobas.hobune.stream/wayback/20220612212510im_/https://answers.unity.com/themes/thub/images/avi.jpg)