this code achieves 2d movement and disables diagonal; the 'if' statement overrides vertical movement when there is horizontal input but I cannot override horizontal movement when vertical input is detected at the same time..I would like to prioritize the direction of the last key pressed (when multiple are pressed at the same time)
public class PlayerMovement : MonoBehaviour
public float moveSpeed = 5f;
public Rigidbody2D rb;
Vector2 movement;
// Update is called once per frame
void Update()
{
// Input
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
//Disable diagonal movement and prioritize direction of last key pressed
if (movement.x != 0) movement.y = 0;
else if (movement.y != 0) movement.x = 0;
}
void FixedUpdate()
{
// Movement
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
Figured it out! All credit to https://stackoverflow.com/users/3214843/manfred-radlwimmer answering basically the same question here: How to stop diagonal movement - Unity 2d?
Here's the specific code needed in this case:
// Disable diagonal movement & prioritize direction of last key pressed
bool isMovingHorizontal = Mathf.Abs(movement.x) > 0.5f;
bool isMovingVertical = Mathf.Abs(movement.y) > 0.5f;
if (isMovingVertical && isMovingHorizontal)
{
if (wasMovingVertical)
{
movement.y = 0;
}
else
{
movement.x = 0;
}
}
else if (isMovingHorizontal)
{
movement.y = 0;
wasMovingVertical = false;
}
else if (isMovingVertical)
{
movement.x = 0;
wasMovingVertical = true;
}
else
{
movement.x = 0;
movement.y = 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.