How do I add a cap to a value to keep it from surpassing a certain number?

So I made a spread variable that starts at 0 for the first shot, and for each shot after it gets added to. When the player stops holding down mousebutton1, it slowly returns to its original value. However, I’m having issues with there being too much spread at the last few shots, and would like to cap it to a specific number.

I triedusing math.min but I’m not really familiar with it so I just did

local Spread = math.min(0, 0.1)

and then it gets added to later where the shooting is done:

Spread = Spread + 0.0175

It returns to its value when it is mouse.button1up. Any solutions?

1 Like
if Spread > VALUE_YOU_WANT then
      Spread = VALUE_YOU_WANT
end

Fire this each time you increase spread to check the value and cap it.

1 Like

I tried that already and it doesn’t seem to work for some reason

Could you explain how it doesn’t seem to work? You need to be more specific than that.

Can I see the full code? I’m not sure where you put it.

				if Ammo ~= 0 and Secondary == false then
					FireGun() 
	                CameraKick()
					Ammo = Ammo - 1
					AmmoCounter.Text = Ammo
					ReserveAmmo.Text = Reserve
					Spread = Spread + 0.0175
					if Spread > 1.5 then
						Spread = 1.5
					end
	mouse.Button1Up:Connect(function()
		buttononedown = false
		print(Spread)
end)

it’s still 0.525 at the end of the magtazine

if Ammo ~= 0 and Secondary == false then
					FireGun() 
	                CameraKick()
					Ammo = Ammo - 1
					AmmoCounter.Text = Ammo
					ReserveAmmo.Text = Reserve
					if Spread + .0175 > 1.5 then
						Spread = 1.5
                    else
                        Spread += .0175
					end

still ends at 0.525, it looks like it should work but for some reason it doesn’t

math.min returns the first parameter given if the first parameter is less than the second parameter given, so you are adding 0.0175 to the spread variable (which is 0 since 0 is less than 0.1) and it keeps adding 0.0175 so it might be bigger than 0.1 .Try this:

local Spread = math.min(0,0.1)
------------------------------
Spread = math.min(Spread+0.0175,0.1)
1 Like

This does everything for you.

Hope it helps.

1 Like

Have you tried using math.clamp?

Spread = math.clamp(Spread, MIN_NUMBER, MAX_NUMBER)

It makes sure that the number does not go above or below a specified number.

2 Likes

This worked, thanks a lot, I’m not really familiar with math functions yet

math.clamp also worked, I tried both solutions

thanks for breaking it down, it also worked