问题描述
IEnumerator Reload(float reloadSpeed)
{
canShoot = false;
yield return new WaitForSeconds(reloadSpeed);
if(totalAmmo >= magazineCapacity)
{
totalAmmo -= magazineCapacity - currentAmmo;
currentAmmo += magazineCapacity - currentAmmo;
}
else if(totalAmmo <= magazineCapacity && (totalAmmo -= magazineCapacity - (magazineCapacity - totalAmmo) - currentAmmo) > 0 )
{
totalAmmo -= magazineCapacity - (magazineCapacity - totalAmmo) - currentAmmo;
currentAmmo += magazineCapacity - (magazineCapacity - totalAmmo) - currentAmmo;
}
else
{
if(totalAmmo + currentAmmo <= magazineCapacity)
{
currentAmmo += totalAmmo;
totalAmmo = 0;
}
else
{
int leftAmmo;
leftAmmo = totalAmmo + currentAmmo - magazineCapacity;
currentAmmo = totalAmmo - leftAmmo;
totalAmmo = leftAmmo;
}
}
canShoot = true;
}
因此,当我尚未重新装填的弹药少于 30 时,我无法重新装填,并且它开始执行随机操作,例如晚上我的 currentAmmo 和 totalAmmo 或升级我的 totalAmmo 不知道如何修复它
解决方法
与其在重新加载时为每一种可能性都做一个案例,这应该是一个更通用的解决方案。 Mathf.Clamp
会阻止你从总弹药中吸取比你拥有的更多的弹药。
IEnumerator Reload(float reloadSpeed)
{
canShoot = false;
yield return new WaitForSeconds(reloadSpeed);
// No ammo? No reload
if (totalAmmo > 0)
{
//Take out the amount of ammo we need. Clamp the amount so that we cant take more than the total ammo
int amountToWithdraw = Mathf.Clamp(magazineCapacity - currentAmmo,magazineCapacity);
totalAmmo -= amountToWithdraw;
currentAmmo += amountToWithdraw;
}
canShoot = true;
}