Hi, I am doing a coursework and I follow the tutorials from my lecturers, but unfortunately I cannot change the fire rate of the bullets. Here is my code:
Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float movementSpeed = 10f;
Rigidbody rigidBody;
public float fireRate = 0.75f;
public GameObject bulletPrefab;
public Transform bulletPosition;
float nextFire;
// Start is called before the first frame update
void Start()
{
rigidBody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
Move();
if (Input.GetKey(KeyCode.Space))
{
Fire();
}
}
void Move()
{
if (Input.GetAxisRaw("Horizontal") == 0 && Input.GetAxisRaw("Vertical") == 0)
return;
var horizontalInput = Input.GetAxis("Horizontal");
var verticalInput = Input.GetAxis("Vertical");
var rotation = Quaternion.LookRotation(new Vector3(horizontalInput, 0 , verticalInput));
transform.rotation = rotation;
Vector3 movementDir = transform.forward * movementSpeed * Time.deltaTime;
rigidBody.MovePosition(rigidBody.position + movementDir);
}
void Fire()
{
if (Time.time > nextFire)
{
nextFire = Time.time + fireRate;
GameObject bullet = Instantiate(bulletPrefab, bulletPosition.position, Quaternion.identity);
bullet.GetComponent<BulletController>()?.InitializeBullet(transform.rotation * Vector3.forward);
}
}
}
BulletController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour
{
Rigidbody rigidBody;
public float bulletSpeed = 15f;
// Start is called before the first frame update
void Awake()
{
rigidBody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
}
public void InitializeBullet(Vector3 originalDirection)
{
transform.forward = originalDirection;
rigidBody.velocity = transform.forward * bulletSpeed;
}
private void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
}
}
Also, when I shoot the first bullet and it take some seconds until I can shoot again, like 3-5 sec.
Thank you in advance.