微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我试图写一个重新加载脚本,但我的逻辑不够好

如何解决我试图写一个重新加载脚本,但我的逻辑不够好

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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。