Help with reload system calculation

So currently i have 2 values, ammo the current ammo that the player can shoot and spareammo, the spare ammo that the user reloads with
however i ran in a small problem and thats the math. Im not really good with maths and what im trying to achieve is if you reload, it gives you as much ammo as possible from spareammo, with a limit of how much it can give (so ammo can only hold 30) then removes however much it gave to ammo from spare ammo so for example:
ammo + 5
spareammo - 5
if ammo is 3 and spareammo has 5 it gives 5 to ammo so 8, and spareammo becomes 0

If someone can make a example calculation or something that would be nice, i also have a modulescript holding the original values so just do Settingmodule.Ammo or .SpareAmmo

--Reload
local ammoMissing = magazineCapacity - magazineQuanitity
local ammoTaken = math.min(reserveAmmo, ammoMissing)
magazineQuantity = magazineQuantity + ammoTaken
reserveAmmo = reserveAmmo - ammoTaken
1 Like

Here’s an example with this kind of ammo system I did, however it isn’t really perfect:

local maxbullets = tool:WaitForChild("MaxBullets") -- Value for Max ammo the gun can hold.
local bullets = tool:WaitForChild("Bullets") -- Value for The amount of bullets inside the in-use magazine.
local reserve = tool:WaitForChild("Reserve") -- Value for Ammo left in reserve.
local oldReserve = reserve.Value -- Get ammo left in reserve
local oldcap = bullets.Value --get the ammo capacity from the gun
if maxbullets and bullets then 
	if oldReserve < (maxbullets.Value - bullets.Value) then
		--If the ammo reserve + current bullets in gun is less than the max ammo the gun can hold 
		--(for example, my M4A1 can hold 30 bullets max but only 3 bullets in magazine and 20 in reserve):
		reserve.Value = 0 --No more bullets in reserve
		bullets.Value = bullets.Value + oldReserve -- add the current bullets inside with the amount of bullets in reserves
	else -- If the gun has more ammo than the amount the of ammo the gun can hold:
		reserve.Value = oldReserve - (maxbullets.Value - oldcap) --Ammo capacity in gun - (max amount of ammo the gun can hold - the old capacity before completing reloading) 
		bullets.Value = maxbullets.Value --set the amount of bullets to the max
	end
end
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.