为什么我的枪的冷却时间不工作?



我有这把枪,应该有一个冷却后每次射击使用time between shots += Time.deltaTime。问题是timeBeetweenShots不会增加。以下是我认为重要的代码部分:

private void Update()
{
timeSinceLastShot += Time.deltaTime;
}
public bool CanShoot() => !gunData.reloading && timeSinceLastShot > 1 / (gunData.fireRate / 60);
public void Shoot()
{
if (gunData.currentAmmo > 0)
{
if (CanShoot())
{
Debug.Log("shooting");
gunData.currentAmmo--;
timeSinceLastShot = 0;
OnGunShot();
}
} else
{
StartCoroutine(Reload());
}
}

我做错了什么?

我想我们可能需要使用Time.time.

文档链接是完美的枪射击间隔。

但是我编辑了你的代码。

using System.Collections;
using UnityEngine;
public class Gun : MonoBehaviour
{
GunData gunData; // gundata might be access from player
float timeSinceLastShot = 0;
private void Update()
{
}
public bool CanShoot() => !gunData.reloading && (timeSinceLastShot + gunData.fireRate) < Time.time;
public void Shoot()
{
if (gunData.currentAmmo > 0)
{
if (CanShoot())
{
Debug.Log("shooting");
gunData.currentAmmo--;
timeSinceLastShot = Time.time;// save the last time that shot
OnGunShot();
}
}
else
{
StartCoroutine(Reload());
}
}
public void OnGunShot()
{ // animation might be here
}
IEnumerator Reload()
{   // relaoding might be here
yield return new WaitForEndOfFrame(); 
}
}
public class GunData // just dummy data 
{
public int currentAmmo = 10;
public float fireRate = 0.2f;
public bool reloading = false;
}

最新更新