I can't shoot while moving diagonally

Hi, I am new to programming and also new to making games in Unity. I’m trying to create a game and I have an issue in my code, but I can’t figure out where the problem is.

In my game, I have a tank that can shoot in every direction if it is not moving. When it is moving in horizontal or vertical directions, it can shoot normally in these directions while moving. However, when it is moving diagonally, it can’t shoot while I’m pressing the space key. The only diagonal direction in which it can move and shoot at the same time is up-right, but in the other three diagonal directions, the tank does not shoot while it is moving, even when I press the space key.

Here is the code:

// paste your code here as text, please

Can someone help me with that? Thank you so much.

It seems like the issue might be related to how you handle shooting when the tank is moving diagonally. In your existing code, you are setting the rb.velocity before checking for shooting, and this might interfere with the shooting logic.

using UnityEngine;

public class TankController : MonoBehaviour
{
    public float moveSpeed = 5.0f;
    public GameObject bulletPrefab;
    public Transform bulletSpawnPoint;

    private Rigidbody2D rb;
    private Vector2 moveDirection;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        // Zpracování pohybu
        float movex = Input.GetAxisRaw("Horizontal");
        float movey = Input.GetAxisRaw("Vertical");
        moveDirection = new Vector2(movex, movey).normalized;

        // Zpracování střelby
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Shoot();
        }

        // Set velocity after shooting logic
        rb.velocity = moveDirection * moveSpeed;

        if (moveDirection != Vector2.zero)
        {
            float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg - 90f;
            rb.rotation = angle;
        }
    }

    void Shoot()
    {
        Instantiate(bulletPrefab, bulletSpawnPoint.position, Quaternion.identity);
    }
}

There’s two possibilities:
1: Your tank is hitting the bullet, instantly destroying it, or some other gameplay feature is making the bullet not appear
2: Your keyboard is suffering from rollover, where it can’t handle all of the relevant keys being pressed at once.

Testing if it’s 1 is pretty simple - add a Debug.Log to your Shoot method. If the log prints to the console, , your code is running, and there’s something else happening.

Testing 2 is also pretty simple - use Online Key Rollover Test - Mechanical Keyboard, and check if you can hold eg. down-left and space and have it show up at the same time.