Why isn't the input working every time?

I have this code:

using System;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerControler : MonoBehaviour
{
    private Rigidbody2D rb;
    private InputAction shoot;
    private bool shooting;
    private Vector3 mouse;
    
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
        shoot = InputSystem.actions.FindAction("Shoot");
    }

    // Physics Update
    void FixedUpdate()
    {
        Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(mouse);
        
        Vector2 direction = mouseWorldPos - rb.position;
        
        rb.rotation = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        if (shooting)
        {
            print("Shoot");
            rb.AddRelativeForce(new Vector2(-200, 0));
        }
    }
    
    void Update()
    {
        mouse = Input.mousePosition;
        shooting = shoot.WasPressedThisFrame();
    }
    
    
}

What i am trying to do is push backwards whenever I shoot. The shoot action is bound to the space key. When I use this code there is a one in three chance that hitting space will actually move my object. I suspect this has something to do with timing between physics and frame updates (so shooting goes to 0 before FixedUpdate() has time to move the object) how can I fix this?

You’d want to flip shooting to true only when false, so this ‘queues’ it up for when the next FixedUpdate rolls around, then flip it back to false in your if-statement.

1 Like

Okay thanks for the help