I’m making a shmup game and obviously one of the most important things of this type of game is if the bullet system is working.
However, the bullets are not coming out in the position they should, which is at the player’s position. Furthermore, multiple bullets are firing at once, making it appear as a continuous line instead of a single one.
Unfortunately, I can’t attach a video showing the problem running, but I have the code.
Here are the lines of code for the player, the gun and the bullet.
using System;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
// This array will hold references to all Gun components that are children of the player
Gun[] guns;
bool shoot;
// This is the input action for moving the player, which can be set up in the Unity editor
public InputAction MoveAction;
public float moveSpeed = 5f;
private Vector2 move;
// Variables for health management
public int maxHealth = 100;
public int health { get { return currentHealth; } }
public int currentHealth;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
guns = transform.GetComponentsInChildren<Gun>();
MoveAction.Enable();
currentHealth = maxHealth;
}
// Update is called once per frame
void Update()
{
move = MoveAction.ReadValue<Vector2>();
// Check if the space key is pressed to shoot
shoot = Keyboard.current.spaceKey.isPressed;
if (shoot)
{
shoot = false;
foreach (Gun gun in guns)
{
gun.Shoot();
}
}
}
void FixedUpdate()
{
Vector2 position = (Vector2)transform.position + (move * 0.1f);
transform.position = position;
}
// This method is called when the player takes damage or heals
public void ChangeHealth(int amount)
{
currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
Debug.Log(currentHealth + "/" + maxHealth);
}
}
using UnityEngine;
public class Gun : MonoBehaviour
{
public Bullet bullet;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
// This method is called when the player shoots
public void Shoot()
{
Bullet spawnedBullet = Instantiate(bullet, transform.position, Quaternion.identity);
Rigidbody2D rb = spawnedBullet.GetComponent<Rigidbody2D>();
}
}
using UnityEngine;
public class Bullet : MonoBehaviour
{
public Vector2 direction = new Vector2(1,0);
public Vector2 velocity;
public float speed = 2f;
Rigidbody2D rb;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.linearVelocity = transform.right * speed;
Destroy(gameObject, 5);
}
// Update is called once per frame
void Update()
{
velocity = direction * speed;
}
private void FixedUpdate()
{
Vector2 position = transform.position;
position += velocity * Time.fixedDeltaTime;
transform.position = position;
}
}