Hello Devforum, i’m creating my gun system and got stuck here when it came to creating a working reloading system. Refilling the weapon’s magazine is no issue to me, but the real problem is that if there’s not enough ammo to refill a magazine entirely, i have barely any idea how to not make it glitch out. I’m really bad at explaining things so here’s a graph of what im talking about:
i think the reason this is happening is because you are only setting the magazine’s ammo to the total amount of ammo that was left, and not accounting for the ammo that was already in the magazine (if that makes any sense).
thanks, this worked, but i need to make it so the maximum amount of ammo in the magazine was under the maxAmmo value, which is 30 in this case. your solution worked here, but it allows the magazine to have the amount of ammo above 30. any idea how do i make it so it left the remaining ammo out of the magazine?
To calculate the amount of ammo to transfer from your reserves, begin by calculating how many rounds are needed to fill the mag:
local ammoDeficit = MAX_AMMO - currentAmmo
Next, we can figure out how much ammo we can transfer by choosing the smaller of two values:
The ammo reserve
The ammo deficit
local ammoTransfer = math.min(ammoReserve, ammoDeficit)
This ensures we’re transferring no more than the ammo deficit. If the deficit is more than what’s in the reserve, we just dump what’s left in the reserve.
Altogether:
local ammoTransfer = math.min(ammoReserve, MAX_AMMO - currentAmmo)
Finally, deduct ammoTransfer from ammoReserve, and add ammoTransfer to currentAmmo