Mathf.Clamp is not Clamping.

Ok, So I have a crosshair that gets bigger, as the gun becomes less accurate. I want it to stop at the lowest accuracy (highest value). I first tried an if statement to check if the current accuracy was greater than the lowest accuracy, and then changed the value, but that ended up being jerky. I got the idea to just use clamping, but it is not working and I can’t understand why. The current accuracy’s value just keeps rising past the lowest accuracy.

CODE:

//Update Loop

Mathf.Clamp(currentAccuracy, highestAccuracy, lowestAccuracy);

if (currentAccuracy >= highestAccuracy && firing == false)
	{
			
		currentAccuracy -= Time.deltaTime * (speedAccuracyIncrease);
			
	}


if(Input.GetButtonDown("Fire1") && autoFire == false || Input.GetButton("Fire1") && autoFire == true)
	{
		if(fireDelay <= 0 && ammoClip > 0)
		{
			firing = true;
		
			if (bullet)
			{
			
				currentAccuracy += accuracyDecrease;

	                }
                   else
	                {
	
		                firing = false;
	
	                 }

P.S

lowestAccuracy has the highest value because it is the least accurate and has the most effect on the raycast’s rotation. Same goes for highestAccuracy.

Also, sorry for the weirdly typed code, I removed a lot of it in the editor so you only see what is important and I kind of screwed it up.

–

1 Answer

1

Clamp works on the Lowest value to highest value, so assuming your code:

Mathf.Clamp(currentAccuracy, lowestAccuracy, highestAccuracy);

Also you need to assign it to a variable, like:

accuracy = Mathf.Clamp(currentAccuracy, lowestAccuracy, highestAccuracy);

And the accuracy will contain your clamped accuracy.

> Also you need to assign it to a > variable Definitely

–

Right, I forgot to assign it to a variable, thanks! Also lowestAccuracy means it is that least accurate. To make the gun less accurate I have to have a HIGHER value to affect the angle randomization of the raycast. That is why I have it as the max. Thanks!

–