using UnityEngine; public class PlayerController2D : MonoBehaviour { // Public variables public float speed = 5f; // The speed at which the player moves public bool canMoveDiagonally = true; // Controls whether the player can move diagonally // Private variables private Rigidbody2D body; // Reference to the Rigidbody2D component attached to the player private SpriteRenderer spriteRenderer; private Vector2 movement; // Stores the direction of player movement private bool isMovingHorizontally = true; // Flag to track if the player is moving horizontally [HideInInspector] public bool frozen; void Start() { // Initialize the Rigidbody2D component body = GetComponent(); spriteRenderer = GetComponent(); // Prevent the player from rotating body.constraints = RigidbodyConstraints2D.FreezeRotation; } void Update() { // Get player input from keyboard or controller float horizontalInput = Input.GetAxisRaw("Horizontal"); float verticalInput = Input.GetAxisRaw("Vertical"); if (frozen) { horizontalInput = 0; verticalInput = 0; } // Check if diagonal movement is allowed if (canMoveDiagonally) { // Set movement direction based on input movement = new Vector2(horizontalInput, verticalInput); } else { // Determine the priority of movement based on input if (horizontalInput != 0) { isMovingHorizontally = true; } // Set movement direction and optionally rotate the player if (isMovingHorizontally) { movement = new Vector2(horizontalInput, 0); } } } void FixedUpdate() { // Apply movement to the player in FixedUpdate for physics consistency body.linearVelocity = movement * speed; float moveX = Input.GetAxisRaw("Horizontal"); if (moveX < 0) { spriteRenderer.flipX = true; } else if (moveX > 0) { spriteRenderer.flipX = false; } } }