Is anyone able to help me with this? I’m trying to make a game using the new Input System used in these videos and trying to implement 4 way directional shooting with arrow keys and movement with WASD. My Input System Actions are Move that have been set to WASD, and Shoot that are set to the arrow keys I can move fine, but when I shoot, sometimes the bullet stops moving and then if I hold an arrow key, then the bullet that had stopped moving will move in the direction of the new arrow key being pressed. I would like for the bullet to just go in the direction it was shot in and continue until it hits something. Here is the code for the bullet. (There's definitely some better way to write this code, and I would love to learn how).
using UnityEngine; using UnityEngine.InputSystem; public class Bullet : MonoBehaviour { Rigidbody2D myRigidBody; [SerializeField] float bulletSpeed = 10f; [SerializeField] float fireDelay; private float lastFire; public InputAction bulletControls; Vector2 shootDirection = Vector2.zero; private void OnEnable()
{ bulletControls.Enable(); } private void OnDisable()
{ bulletControls.Disable(); }
void Start() { myRigidBody = GetComponent<Rigidbody2D>(); } void Update() { if(Time.deltaTime > lastFire + fireDelay) { Shoot(shootDirection); lastFire = Time.deltaTime; } } void Shoot(Vector2 direction) { shootDirection = bulletControls.ReadValue<Vector2>(); myRigidBody.velocity = new Vector2(shootDirection.x * bulletSpeed, shootDirection.y * bulletSpeed); } private void OnTriggerEnter2D(Collider2D other)
{ if(other.tag == "Enemy") { Destroy(other.gameObject); } Destroy(gameObject); } private void OnCollisionEnter2D(Collision2D other)
{ Destroy(gameObject);
} }